1

I wish to generate a list with these value:

[0,0.01,0.02...0.49]

and I though that this was the correct way to do it:

[0.01*i for i in range(50)]

But to my horror I observed the following:

>>> 35*0.01
0.35000000000000003
>>> float("0.35")
0.35

What am I doing wrong? If I understand correctly It seems 35*0.01 does not give the closest floating point representation of 0.35 but float("0.35") does.

Baz
  • 12,713
  • 38
  • 145
  • 268
  • 2
    That's because floating point arithmetic is not all that accurate. Try `format(0.01, '.53f')` to see what is *really* there. – Martijn Pieters Apr 14 '15 at 21:00
  • 2
    Floating point values are **approximations** using binary fractions (0 or 1 * 1/2 + 0 or 1 * 1/4 + 0 or 1 * 1/8, etc) and `0.01` cannot be precisely expressed in such fractions. – Martijn Pieters Apr 14 '15 at 21:01
  • `0.5` is not in the included, you know that right? Because you used `range(50)`. – Malik Brahimi Apr 14 '15 at 21:02
  • @Martijn Pieters This is not a duplicate as I understand that floating points are not perfectly accurate for certain numbers. Rather, it is wrong of me to multiply by 0.01 and I should instead be dividing by 100.0. – Baz Apr 14 '15 at 21:07
  • 1
    @Baz: it is an approach that indeed works for you; the answer there still explains *why you got your output*. Mark's answer is a nice deduction, but at issue is still that you are getting expected floating point artifacts. `0.35` is also not precisely modelled, but Python's representation of the value hides that fact because it is closer to the value than `35 * 0.01` is. – Martijn Pieters Apr 14 '15 at 21:09
  • @Baz: you'll still need to account for those minute differences elsewhere in your code. You produced floating point numbers, if you need to test for equality you need to know about the pecularities. – Martijn Pieters Apr 14 '15 at 21:10
  • 1
    @Baz just so you know, even dividing by 100.0 will not give you a 100 percent accurate representation. It's just *slightly closer* to the actual value of 0.35. It's actually as close as it can get for floating point representation, but it will never be perfect. – Shashank Apr 14 '15 at 21:10
  • 1
    Here's what I mean by this: `35/100.0 == .35` is `True`. `35*0.01 == .35` is `False`, but `format(.35, '.17f')` is clearly not what humans and mathematicians think of as .35 :) – Shashank Apr 14 '15 at 21:14

1 Answers1

7

To guarantee the nearest valid floating point number, you need to start with values that are exact. 0.01 isn't exact, but 100.0 is.

[i/100.0 for i in range(50)]
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622