Bobo Bobo - 1 year ago 86
Python Question

Lists in Python last element

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]
[ 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?

Answer Source

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]
>>> x[-1]

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download