簡體   English   中英

相同代碼在python3和python2之間的運行結果不同

[英]different run results between python3 and python2 for the same code

當我在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)

在Python 2和3中運行時值發生變化的原因是/運算符的執行方式取決於所運行程序的版本。在PEP 238中可以了解到該信息,其中詳細說明了在python 3中發生的更改

為了確保在python 2和python 3中都能獲得相同的結果,請在使用python 2時使用以下import語句:

from __future__ import division

這樣可以確保您的代碼與python的兩個版本兼容。

問題就在這條線上:

temp1 = temp_phi / e

在Python 2中, /運算符的兩個參數均為整數時,將執行整數除法。 也就是說,從概念上講,它等效於floor(float(a)/ float(b)) ,其中ab是其整數參數。 在Python 3中, /是浮點除法,而不考慮其參數的類型,並且Python 2中/的行為由//運算符重新創建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM