Step error in np.arange

Asked

Viewed 54 times

0

I have a problem in the arange that does not return accurate values.

import numpy as np
for i in np.arange(0.0, 5.0, 0.2 ):
      print(i)

The result is: 0.0 0.2 0.4 0.6000000000000001 0.8 1.0 1.2000000000000002 1.4000000000000001 1.6 1.8 2.0 2.2 2.4000000000000004 2.6 2.8000000000000003 3.0 3.2 3.4000000000000004 3.6 3.8000000000000003 4.0 4.2 4.4 4.6000000000000005 4.800000000000001

That is, it should return 0.0, 0.2, 0.4, 0.6, 0.8...but is creating numbers with many decimal places after the 3rd iteration.

  • Read this here - it’s important. Very important. https://floating-point-gui.de/

1 answer

1


This is because Python uses floating-point arithmetic, which cannot represent exactly some numbers, and np.arange works by repeatedly adding the step value to the initial value, and this leads to inaccuracy at the end.

You can circumvent this by rounding the values to the required accuracy (from one decimal place in this case):

for i in np.arange(0.0, 5.0, 0.2):
    print(round(i,1))

Or, by convenience, can create a function that already creates in the right way:

def arange(inicio, fim, passo):
    return passo * np.arange(inicio / passo, fim / passo)

Thus:

for i in arange(0.0, 5.0, 0.2):
      print(i)

Returns the expected values.

I hope I’ve helped :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.