Python_22_ZY笔记_2_Python 2: Floating point division

总目录


一、问题

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中运行,就不会出现问题了。

你可能感兴趣的:(Python_22_ZY笔记_2_Python 2: Floating point division)