【问题标题】:Cannot make Python 3 function work in Python 2.7.12无法使 Python 3 函数在 Python 2.7.12 中工作
【发布时间】: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


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:

      在 Python 2 中,当两个操作数都是整数时,/ 的除法会进行整数除法; 1/20。在 Python 3 中,/ 总是进行正确的除法 (1/2 == 0.5),// 进行整数除法。

      在脚本顶部添加 from __future__ import divison 以获得 Python 3 行为。

      【讨论】:

      • 你比我快 3 秒 :) 也许值得补充一下,在 python 3 中,这个操作变成了一个适当的除法并产生一个浮点数
      • 因此,您不必从 future 导入除法,只需使用 n/2.0 和 0.5 而不是 (1/2)。 :D
      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      相关资源
      最近更新 更多