1

I am using a numpy arange.

[In] test = np.arange(0.01, 0.2, 0.02)
[In] test
[Out] array([0.01, 0.03, 0.05, 0.07, 0.09, 0.11, 0.13, 0.15, 0.17, 0.19])

But then, if I iterate over this array, it iterates over slightly smaller values.

[In] for t in test:
....     print(t)
[Out] 
0.01
0.03
0.049999999999999996
0.06999999999999999
0.08999999999999998
0.10999999999999997
0.12999999999999998
0.15
0.16999999999999998
0.18999999999999997

Why is this happening?

To avoid this problem, I have been rounding the values, but is this the best way to solve this problem?

for t in test:
    print(round(t, 2))
usernumber
  • 1,958
  • 1
  • 21
  • 58

2 Answers2

1

I think the nature of the floating point numbers mentioned in the comments is the issue.

If you still think you're afraid of leaving it that way I suggest that you multiply your numbers by 100 and so work with intergers:

test = np.arange(1, 20, 2)
print(test)

for t in test:
    print(t / 100)

This gives me the following output:

[ 1  3  5  7  9 11 13 15 17 19]
0.01
0.03
0.05
0.07
0.09
0.11
0.13
0.15
0.17
0.19

Alternatively you can also try the following:

test = np.arange(1, 20, 2) / 100
Stan
  • 250
  • 2
  • 9
0

Did you try:

test = np.arange(0.01, 0.2, 0.02, dtype=np.float32)
FBruzzesi
  • 6,385
  • 3
  • 15
  • 37