1
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
IPython 5.6.0 -- An enhanced Interactive Python.
In [1]: import numpy as np

In [2]: np.__version__
Out[2]: '1.14.3'

In [3]: np.arange(1.1, 1.12, 0.01)
Out[3]: array([1.1 , 1.11, 1.12])

In [4]: np.arange(1.1, 1.13, 0.01)
Out[4]: array([1.1 , 1.11, 1.12])

In both cases, the array gets to 1.12... how would you explain that?

eelioss
  • 359
  • 1
  • 5
  • 10

1 Answers1

4

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])
zvone
  • 18,045
  • 3
  • 49
  • 77