Search code examples
python-2.7functionpython-3.xnewtons-method

Cannot make Python 3 function work in Python 2.7.12


I use Python 2.7.12; the book of algorithms I'm studying uses Python 3. Until now I've found that I could easily change most of the algorithms to Python 2, but this square root function, using Newton's Law, still eludes me.

Here is the code, in its original Python 3.

def square_root(n):
    root = n / 2 #initial guess will be 1/2 of n
    for k in range(20):
        root = (1 / 2) * (root + (n / root))
    return root

And here is the error when I try to call the function in Python 2.7.12:

print square_root(9)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in square_root
ZeroDivisionError: integer division or modulo by zero

I'd like to know how to write this function for Python 2.7.


Solution

  • In Python 2, division with / does integer division when both operands are integer; 1/2 is 0. In Python 3, / always does proper division (1/2 == 0.5) and // does integer division.

    Add from __future__ import divison at the top of your script to get the Python 3 behavior.