0

As you can see here, np.arange returns an array with the values from the first to the last (But no the last!) with a separation you choose.

My examples:

In[600]: np.arange(1,11,1)
Out[600]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])


In [602]: np.arange(1,4,0.2)
Out[602]: array([ 1. ,  1.2,  1.4,  1.6,  1.8,  2. ,  2.2,  2.4,  2.6,  2.8,  3. ,
    3.2,  3.4,  3.6,  3.8])


In [604]: np.arange(3.24,3.6,0.04)
Out[604]: array([ 3.24,  3.28,  3.32,  3.36,  3.4 ,  3.44,  3.48,  3.52,  3.56])

But:

In [605]: np.arange(14.04, 14.84, 0.08)
Out[605]: array([ 14.04,  14.12,  14.2 ,  14.28,  14.36,  14.44,  14.52,  14.6 ,
    14.68,  14.76,  14.84])

What is wrong with this last one? Why does it returns 14.84 instead of stopping at 14.76?

I have been observing that it happens sometimes, but im not able to see a patron or so. What´s going on?

  • 3
    Note also that they recognize it in the documentation: "When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases." – lib Nov 21 '15 at 16:58

1 Answers1

2

It's floating point precision, e.g. see this question: python numpy arange unexpected results

You could get around it like so:

>>> np.arange(14.04, 14.839, 0.08)
array([ 14.04, 14.12, 14.2, 14.28, 14.36, 14.44, 14.52, 14.6, 14.68, 14.76])

...but this is pretty hacky. It's usually a better idea to use numpy.linspace(), but then you have to give the number of steps, not the interval, so it can be a bit of a pain.

>>> np.linspace(14.04, 14.76, 9)
array([ 14.04,  14.13,  14.22,  14.31, 14.4, 14.49,  14.58, 14.67, 14.76])

Choose your poison!

Community
  • 1
  • 1
Matt Hall
  • 7,614
  • 1
  • 23
  • 36