Python_22_ZY筆記_2_Python 2: Floating point division

<a href="http://www.lxweimin.com/p/54870e9541fc">總目錄</a>


一、問題

Python 2 默認的/是integer division, 所以在計算結果需要floats的時候,要做一下處理

  • 被除數如果知道是多少,比如88,就寫成88.0或者88.
  • 被除數如果是變量,就要乘以1.0

看起來很簡單的問題,但是在實際操作中很容易就弄錯了。

比如在speed_fraction這個練習中:

# -*- coding: utf-8 -*-

# Write a procedure, speed_fraction, which takes as its inputs the result of
# a traceroute (in ms) and distance (in km) between two points. It should
# return the speed the data travels as a decimal fraction of the speed of
# light.

speed_of_light = 300000. # km per second


def speed_fraction(traceroute, distance):
    speed = distance / (traceroute*1.0/2/1000.)
    print "Correct traceroute*1.0/2/1000.", traceroute/2/1000.
    print "Correct speed", speed
    return speed / (speed_of_light)


def speed_fraction_wrong(traceroute, distance):
    speed = distance / (traceroute/2/1000.)
    print "WRONG traceroute/2/1000.", traceroute/2/1000.
    print "WRONG speed", speed
    result = speed / speed_of_light
    return result


def speed_fraction_1(traceroute, distance):
    speed = distance / (traceroute/2000.)
    print "Correct traceroute/2000.", traceroute/2/1000.
    print "Correct speed", speed
    result = speed / speed_of_light
    return result




print speed_fraction(50,5000), "\n\n"
#>>> 0.666666666667

print speed_fraction(50,10000), "\n\n"
#>>> 1.33333333333  # Any thoughts about this answer, or these inputs?

print speed_fraction(75,4500), "\n\n"
#>>> 0.4

print "WRONG %s" % speed_fraction_wrong(50,5000), "\n\n"
#>>> 0.666666666667

print "WRONG %s" % speed_fraction_wrong(50,10000), "\n\n"
#>>> 1.33333333333  # Any thoughts about this answer, or these inputs?

print "WRONG %s" % speed_fraction_wrong(75,4500), "\n\n"
#>>> 0.4

print "speed_fraction_1 %s" % speed_fraction_1(75,4500), "\n\n"
#>>> 0.4

Console:

Correct traceroute*1.0/2/1000. 0.025
Correct speed 200000.0
0.666666666667 


Correct traceroute*1.0/2/1000. 0.025
Correct speed 400000.0
1.33333333333 


Correct traceroute*1.0/2/1000. 0.037
Correct speed 120000.0
0.4 


WRONG traceroute/2/1000. 0.025
WRONG speed 200000.0
WRONG 0.666666666667 


WRONG traceroute/2/1000. 0.025
WRONG speed 400000.0
WRONG 1.33333333333 


WRONG traceroute/2/1000. 0.037
WRONG speed 121621.621622
WRONG 0.405405405405 


Correct traceroute/2000. 0.037
Correct speed 120000.0
speed_fraction_1 0.4 



Process finished with exit code 0

二、癥結

問題的癥結所在:

  • speed = distance / (traceroute*1.0/2/1000.) 對;
  • speed = distance / (traceroute/2000.)
  • speed = distance / (traceroute/2/1000.) 錯;
  • 即使 (traceroute*1.0/2/1000.)(traceroute/2000.)(traceroute/2/1000.) 結果都是0.037

很有意思,不過python2這點也真的很搞... 總之見到被除數就乘以1.0好了,萬一出問題debug起來可是很傷神啊。

三、參考

  • 這個網站很好地比較了Python3 和 Python2,如果上述代碼在Python3中運行,就不會出現問題了。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容