【问题标题】:Range with floating point numbers and negative steps具有浮点数和负步长的范围
【发布时间】:2016-05-13 20:42:38
【问题描述】:

我编写了以下内容来创建具有负浮点步长的范围:

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

但是r = myRange(1,0,-0.1)的输出

看起来很奇怪

>>> 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

最后一个数字是从哪里来的?为什么不是0?

【问题讨论】:

标签: python range generator yield


【解决方案1】:

并非所有floating point numbers 都可以准确表示。例如,这是 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

一种解决方案可能是四舍五入:

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)

输出:

1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0.0

【讨论】:

    猜你喜欢
    • 2011-05-10
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多