Reputation: 21
I thought that in arange the second argument will never be comprised in the list, but see what happens in 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 ?
Upvotes: 2
Views: 203
Reputation: 7688
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.
To see more about the limitations of floats, look at Python's tutorial.
Upvotes: 4
Reputation: 13549
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.
Upvotes: 4