Because of floating point error, 1.1
, 0.01
and 0.12
are not as precise as one might expect, nor are mathematical operations between them. For example:
>>> 1.1 + 0.01 + 0.01 + 0.01
1.1300000000000001
See also:
>>> decimal.Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> decimal.Decimal(1.12)
Decimal('1.12000000000000010658141036401502788066864013671875')
If they were precise, np.arange(1.1, 1.12, 0.01)
would be array([1.1 , 1.11])
np.arange
specification mentions that as well: For the stop
argument it writes:
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.
You can avoid the problem by always specifying an upper limit which is between two steps, rather than exactly on the boundary:
>>> np.arange(1.1, 1.115, 0.01)
array([1.1 , 1.11])
>>> np.arange(1.1, 1.125, 0.01)
array([1.1 , 1.11, 1.12])
>>> np.arange(1.1, 1.135, 0.01)
array([1.1 , 1.11, 1.12, 1.13])