2

I am new to python and I tried this:

import numpy as np

x = np.arange(0.7,1.3,0.1)
print (x)
y = np.arange(0.6,1.3,0.1)
print (y)

The output was [ 0.7 0.8 0.9 1. 1.1 1.2 1.3] and [ 0.6 0.7 0.8 0.9 1. 1.1 1.2]. Why in the first case 1.3 appears in the list and in the second case it doesn't?

Silviu
  • 749
  • 3
  • 7
  • 17

3 Answers3

6

This is due to rounding errors. If you actually print the last element in x in it's full precision, you'll see that it is smaller than 1.3:

>>> import numpy as np
>>> x = np.arange(0.7,1.3,0.1)
>>> 1.3 > x[-1]
True
>>> x[-1]
1.2999999999999998

Note, as stated 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.:

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    Though rounding could be issue, I think documentation reference is better answer, because why the same rounding issue didn't occur in first example? – kosa Aug 30 '16 at 19:10
  • 1
    @Nambari -- Yeah, unless you're an IEEE 754 guru (which I'm not), it's hard to predict exactly how the rounding error will mess with you which is why I added a link to the docs and the relevant blurb to my answer. – mgilson Aug 30 '16 at 19:12
4

arange is not suitable for floating point numbers:

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.

I'm not familiar with the internals of numpy, but my guess is that this is a side effect of floating point numbers not being exact (meaning that they can't exactly represent some values).

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
1

See the numpy.arange documentation here:

specifically "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"

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
perfect5th
  • 1,992
  • 1
  • 17
  • 18