具有浮点数和负步数的范围

时间:2016-02-04 09:48:48

标签: python range generator yield

我编写了以下内容,用于创建具有负浮点步骤的范围:

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?

1 个答案:

答案 0 :(得分:2)

并非所有floating point numbers都可以准确表示。例如,这是Python 3.5的输出:

        var innerQuery = ParseObject.GetQuery ("Codes")
            .WhereEqualTo ("status", "red");
        var query = ParseObject.GetQuery ("Events")
            .WhereMatchesQuery ("code", innerQuery);
        IEnumerable<ParseObject> results = await query.FindAsync();

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

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)