带浮点数和负阶跃的范围 [英] Range with floating point numbers and negative steps

查看:146
本文介绍了带浮点数和负阶跃的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是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?

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

推荐答案

并非所有浮点数可以准确表示.例如,这是Python 3.5的输出:

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)

输出:

1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0.0

这篇关于带浮点数和负阶跃的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆