python中arange的奇怪行为

[英]strange behaviour of arange in python


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的教程。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/01/23/a7b5eed15bc5cf4fa18419010cf2e83b.html



 
  © 2014-2022 ITdaan.com 联系我们: