0

I wrote this code and quite unexpectedly ran into this

for i in range(9):
    x = np.arange(i+0.8, i+1.3, 0.1)
    print(i, x)

this is output

0 [0.8 0.9 1.  1.1 1.2]
1 [1.8 1.9 2.  2.1 2.2]
2 [2.8 2.9 3.  3.1 3.2]
3 [3.8 3.9 4.  4.1 4.2]
4 [4.8 4.9 5.  5.1 5.2]
5 [5.8 5.9 6.  6.1 6.2]
6 [6.8 6.9 7.  7.1 7.2]
7 [7.8 7.9 8.  8.1 8.2 8.3]
8 [8.8 8.9 9.  9.1 9.2]

Why is the 7th row like this?

Why exactly in the 7th row?

1 Answers1

1

Adding 0.1 is not a good idea

In general, decimal fractions do not fit nicely into binary floating point formats.

Try starting with integers, and then dividing by 10

for i in range(9):
    x = np.arange(10*i+8, 10*i+13, 1) / 10
    print(i, x)

Result

0 [0.8 0.9 1.  1.1 1.2]
1 [1.8 1.9 2.  2.1 2.2]
2 [2.8 2.9 3.  3.1 3.2]
3 [3.8 3.9 4.  4.1 4.2]
4 [4.8 4.9 5.  5.1 5.2]
5 [5.8 5.9 6.  6.1 6.2]
6 [6.8 6.9 7.  7.1 7.2]
7 [7.8 7.9 8.  8.1 8.2]
8 [8.8 8.9 9.  9.1 9.2]

Always try to use integers for loop control etc.

You can fudge things for decimals by adding "a little extra" but in general it only leads to hard-to-discover bugs later.

Quick demonstration

print(0.1+0.2 == 0.3)

You might think this should be True, but it is False.

This is because there is a tiny difference, due to the rounding errors in trying to represent round decimals in binary.

print(0.1+0.2 -0.3)

5.551115123125783e-17

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26