Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists in Python last element [duplicate]

Tags:

python

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?

like image 876
Silviu Avatar asked Mar 01 '26 23:03

Silviu


2 Answers

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.:

like image 177
mgilson Avatar answered Mar 03 '26 14:03

mgilson


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).

like image 42
MatsLindh Avatar answered Mar 03 '26 14:03

MatsLindh