Why are the values different when iterating them in a for loop, than when printing the whole array?

Emil :

In Python, using numpy, the values change for printing them in an iterating process, or printing the whole array, why, and how can I fix this? I would like them to be e.g. 0.8 instead of 0.799999999...

>>> import numpy as np
>>> b = np.arange(0.5,2,0.1)
>>> for value in b:
...     print(value)
... 
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
1.1999999999999997
1.2999999999999998
1.4
1.4999999999999998
1.5999999999999996
1.6999999999999997
1.7999999999999998
1.8999999999999997
>>> print(b)
[0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
>>> 
enigma :

This happens because Python and NumPy use floating point arithmetic where some numbers, i.e. 0.1, cannot be represented exactly. Also check python floating-point issues & limitations.

You can use Numpy's np.around for this:

>> b = np.around(b, 1) # first arg is the np array, second arg is the no. of decimal points
>> for value in b:
      print(value)

0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=8187&siteId=1