0

I want to create a list such as this one in Python:

[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]

But when I use this method:

z = [x * 0.1 for x in range(0, 11)]

I get this output:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9, 1.0]

How can I create my desired list without these errors?

AMRG
  • 3
  • 1
  • 2

1 Answers1

0

Those errors are a fact of life for binary floating point numbers. You can force Python to use decimal arithmetic with the decimal module:

import decimal
z = [decimal.Decimal(i) / decimal.Decimal(10) for i in range(0, 11)]
Will Angley
  • 1,392
  • 7
  • 11