2

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]
>>> 
Emil
  • 25
  • 3
  • 1
    It's just the way numbers are shown in the list with their respective approximation, once added to the list I think your concern is that you lose precision. – Cristofor Feb 24 '20 at 11:30

4 Answers4

3

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
enigma
  • 111
  • 5
1

To print you can use print format - "%.1f"

>>> for value in b:
...      print("%.1f" %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
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
0

you can use round to get whole number

for value in b:
       print(round(value,2))
0

What i think is, that the method __str__ for the ndarray is implemented that way. There is nothing strange about that behaviour - when you use

print(b)

the function __str__ is called for readability. During this call you operate on ndarray. When you make print in for loop, you use __str__ of float number, which prints the number as it is.

Hope that it is clear, but this can be actually helpful.

:)

Dawid Gacek
  • 544
  • 3
  • 19