Bobo - 1 month ago 5x

Python Question

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]`

Answer

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

Source (Stackoverflow)

Comments