【发布时间】:2017-05-30 01:10:47
【问题描述】:
我使用 Python 2.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 编写这个函数。
【问题讨论】:
标签: python-2.7 function python-3.x newtons-method