无法使 Python 3 函数在 Python 2.7.12 中工作
Cannot make Python 3 function work in Python 2.7.12
我用的是Python2.7.12;我正在学习的算法书使用 Python 3。直到现在我发现我可以轻松地将大多数算法更改为 Python 2,但是这个平方根函数,使用牛顿定律,仍然躲避我。
这是原始代码 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
这是我尝试调用 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
我想知道如何为 Python 2.7 编写此函数。
在Python2中,当两个操作数都是整数时,用/
进行除法; 1/2
是 0
。在 Python 3 中,/
总是做适当的除法 (1/2 == 0.5
) 而 //
做整数除法。
在脚本顶部添加 from __future__ import divison
以获得 Python 3 行为。
在 Python 2 中两个整数相除将始终是一个整数,而在 Python 3 中它将是一个浮点数。要修复算法,强制 python 使用浮点操作数:
def square_root(n):
root = n / 2.0 #initial guess will be 1/2 of n
for k in range(20):
root = (1.0 / 2) * (root + (n / root))
return root
我用的是Python2.7.12;我正在学习的算法书使用 Python 3。直到现在我发现我可以轻松地将大多数算法更改为 Python 2,但是这个平方根函数,使用牛顿定律,仍然躲避我。
这是原始代码 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
这是我尝试调用 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
我想知道如何为 Python 2.7 编写此函数。
在Python2中,当两个操作数都是整数时,用/
进行除法; 1/2
是 0
。在 Python 3 中,/
总是做适当的除法 (1/2 == 0.5
) 而 //
做整数除法。
在脚本顶部添加 from __future__ import divison
以获得 Python 3 行为。
在 Python 2 中两个整数相除将始终是一个整数,而在 Python 3 中它将是一个浮点数。要修复算法,强制 python 使用浮点操作数:
def square_root(n):
root = n / 2.0 #initial guess will be 1/2 of n
for k in range(20):
root = (1.0 / 2) * (root + (n / root))
return root