python中arange的奇怪行为

时间:2021-11-23 13:50:37

I thought that in arange the second argument will never be comprised in the list, but see what happens in Python 2.7.3.

我认为在范围内第二个参数永远不会包含在列表中,但是看看Python 2.7.3中会发生什么。

>>> import numpy
>>> numpy.arange(0.2,0.9,0.1)
array([ 0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8])
>>> numpy.arange(0.2,0.7,0.1)
array([ 0.2,  0.3,  0.4,  0.5,  0.6])
>>> numpy.arange(0.2,0.6,0.1)
array([ 0.2,  0.3,  0.4,  0.5])

but

>>> numpy.arange(0.2,0.8,0.1)
array([ 0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8])

Does anybody know the reason for this behaviour ?

有人知道这种行为的原因吗?

2 个解决方案

#1


4  

In [169]: val = 0.2

In [170]: for i in range(6): #simulating the loop in arange.
   .....:     val += 0.1
   .....:

In [171]: val
Out[171]: 0.7999999999999999

floating point rounding error. The result being that the last value is also printed.

浮点舍入误差。结果是还打印了最后一个值。

#2


4  

This is a problem with floating-point precision.

这是浮点精度的问题。

From the documentation:

从文档:

stop : number

停止:数字

End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

间隔结束。间隔不包括此值,除非在某些情况下,step不是整数,浮点舍入会影响out的长度。

To see more about the limitations of floats, look at Python's tutorial.

要了解有关浮点数限制的更多信息,请查看Python的教程。

#1


4  

In [169]: val = 0.2

In [170]: for i in range(6): #simulating the loop in arange.
   .....:     val += 0.1
   .....:

In [171]: val
Out[171]: 0.7999999999999999

floating point rounding error. The result being that the last value is also printed.

浮点舍入误差。结果是还打印了最后一个值。

#2


4  

This is a problem with floating-point precision.

这是浮点精度的问题。

From the documentation:

从文档:

stop : number

停止:数字

End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

间隔结束。间隔不包括此值,除非在某些情况下,step不是整数,浮点舍入会影响out的长度。

To see more about the limitations of floats, look at Python's tutorial.

要了解有关浮点数限制的更多信息,请查看Python的教程。