0

I have the following loop.

x_array = []

for x in np.arange(0.01, 0.1, 0.01 ):
    
    x_array.append(x)

Why are some of the elements in x_array in so many decimals?

[0.01,
 0.02,
 0.03,
 0.04,
 0.05,
 0.060000000000000005,
 0.06999999999999999,
 0.08,
 0.09]
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
RJL
  • 341
  • 1
  • 7
  • 19

1 Answers1

1

If you want your list of numbers without "additional" digits in the fractional part, try the following code:

x_array = np.arange(0.01, 0.1, 0.01).round(2).tolist()

As you see, you don't even need any explicit loop.

The result is just what you want, i.e.:

[0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09]

Another choice is:

x_array = (np.arange(1, 10) / 100).tolist()
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41