python numpy产生意外结果

2024-05-14 13:57:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用arange函数来定义for循环迭代并获得意外的结果。

i = arange(7.8,8.4,0.05)
print i

是的,包括:

[ 7.8   7.85  7.9   7.95  8.    8.05  8.1   8.15  8.2   8.25  8.3   8.35 8.4 ]

但是使用8.35的停止值如下

i = arange(7.8,8.35,0.05)

产生以下结果

[ 7.8   7.85  7.9   7.95  8.    8.05  8.1   8.15  8.2   8.25  8.3 ]

但我希望我的射程在8.35结束!我知道我可以使用>;8.35和<;8.4的停止值来实现我的结果,但为什么它不同,而且在我看来,不一致?

编辑:我正在使用2.7版


Tags: 函数ltgt编辑for定义printarange
3条回答

我猜你看到了浮点舍入的效果。

numpy.arange与python的range做了相同的事情:它不包含“端点”。(例如,range(0, 4, 2)将产生[0,2],而不是[0,2,4]

但是,对于浮点步骤,舍入误差是累积的,有时最后一个值实际上包括端点。

arange文档中所述:

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.

numpy.linspace在起点和终点之间生成指定数量的点。顺便说一下,默认情况下,它确实包括端点。

或许这与浮点数的限制有关。由于机器精度的原因,不可能将所有可能的值完美地存储为浮点。例如:

>>> 8.4
8.4000000000000004
>>> 8.35
8.3499999999999996

所以,8.4作为一个浮点数比8.4的实际值稍大,而8.35作为一个浮点数稍微少一点。

阿兰格函数的帮助说

    For floating point arguments, the length of the result is
    ``ceil((stop - start)/step)``.  Because of floating point overflow,
    this rule may result in the last element of `out` being greater
    than `stop`.

对于Python2.7,浮点数字和字符串之间的转换现在在大多数平台上都是正确的四舍五入的。

在2.7中

>>> float(repr(2.3))
2.3

在2.6中

>>> float(repr(2.3))
2.2999999999999998

相关问题 更多 >

    热门问题