<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中運行,就不會出現問題了。