0

While I was learning about range() function, I got curious whether I can use range() for float numbers. Stumbled upon below:

i = 0.0
while i <= 1.0:
    print(i)
    i = i + 0.1

When I tried to run it, it did not give the result I expected. Why does it add slightly more/less than 0.1 in some steps? Want to know why python behaves like that to avoid this kind of issues in future.

The result:

> 0.1
> 0.2
> 0.30000000000000004
> 0.4
> 0.5
> 0.6
> 0.7999999999999999
> 0.8999999999999999
> 0.9999999999999999
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    Konstantin, there’s a lot of good details at the link above or by going here: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Maurice Reeves May 30 '22 at 01:08
  • 1
    Hello @MauriceReeves, I know it's probably obvious to everybody here (because it was answered before, of course), but how do you guys find something as specific so quickly? Is there a trick for that? I'm new to the website, and when I search I just get all kinds of things :( is this just experience? – Konstantin Andreyev May 30 '22 at 01:36
  • it is experience and Google or browser remeber which pages we visited before and it suggests the same or similar pages when we search something. – furas May 30 '22 at 01:55
  • 2
    And for old timers like me ... just knowing that questions about floating point inaccuracy have been asked a bazzilion times before over the lifetime of StackOverflow. This topic is something that every programmer **ought to be taught** in their "introduction to programming" course. Unfortunately ... – Stephen C May 30 '22 at 02:20

0 Answers0