Range with floating point numbers and negative steps

半城伤御伤魂 提交于 2019-12-12 06:37:39

问题


I wrote the following for creating a range with negative floating point steps:

def myRange(start, stop, step):
    s = start
    if step < 0:
        while s > stop:
            yield s
            s += step
    if step > 0:
        while s < stop:
            yield s
            s += step

But the output of r = myRange(1,0,-0.1)

looks rather strange

>>> r = myRange(1,0,-0.1)
>>> for n in r: print n
... 
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
1.38777878078e-16

where does this last number come from? And why is it not 0?


回答1:


Not all floating point numbers can be represented exactly. For example, this is the output with Python 3.5:

1
0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457e-16

One solution could be rounding:

def myRange(start, stop, step):
    s = start
    if step < 0:
        while s > stop:
            yield s
            s += step
            s = round(s, 15)
    if step > 0:
        while s < stop:
            yield s
            s += step
            s = round(s, 15)

r = myRange(1,0,-0.1)
for n in r: 
    print(n)

Output:

1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0.0


来源:https://stackoverflow.com/questions/35197598/range-with-floating-point-numbers-and-negative-steps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!