【问题标题】:different run results between python3 and python2 for the same codepython3和python2对于相同代码的不同运行结果
【发布时间】:2018-11-18 05:51:44
【问题描述】:

当我在 python3 中运行这个 python 代码时,它显示了与 python2 不同的结果?为什么会有不同的值?

    d = 0
    x1 = 0
    x2 = 1
    y1 = 1
    e=125
    phi=238
    temp_phi = phi

    while e > 0:
        print (e, temp_phi)
        temp1 = temp_phi / e
        print (temp1)
        temp2 = temp_phi - temp1 * e
        print (temp2)
        temp_phi = e
        e = temp2

        x = x2 - temp1 * x1
        y = d - temp1 * y1

        x2 = x1
        x1 = x
        d = y1
        y1 = y
    print (d + phi)
    if temp_phi == 1:
         print (d + phi)

【问题讨论】:

  • 因为temp1 = temp_phi / e 的划分你在里面。
  • 当两个操作数都是整数时,/ 运算符从整数除法更改为(例如floor(x/y)(x//y))返回一个浮点数(例如相当于Python2 的float(x)/y
  • 除法在 python 2 和 3 中的工作方式不同:stackoverflow.com/questions/21316968/…

标签: python python-3.x variables floating-point iteration


【解决方案1】:

问题出在这一行:

temp1 = temp_phi / e

在 Python 2 中,/ 运算符在其两个参数都是整数时执行整数除法。也就是说,它(在概念上)等价于 floor(float(a) / float(b)),其中 ab 是它的整数参数。在 Python 3 中,/ 是浮点除法,无论其参数的类型如何,Python 2 中 / 的行为由 // 运算符重新创建。

【讨论】:

  • Nitpick:虽然a / b 在概念上等同于floor(float(a) / float(b)),但由于浮点类型的不精确性和有限范围,它实际上并不等同于大整数a 和@ 987654329@.
【解决方案2】:

在 Python 2 和 3 中运行时值发生变化的原因是 / 运算符的执行取决于程序运行的版本。这可以在 PEP 238 中阅读,其中详细说明了变化这发生在 python 3

为确保在 python 2 和 3 中达到相同的结果,请在使用 python 2 时使用以下 import 语句:

from __future__ import division

这可确保您的代码与两个版本的 python 兼容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多