2
start = 0.65

end = 0.75

step = 0.01

while start <= end:

    print (start)

    start += step

But why am I getting below? really

0.65

0.66

0.67

0.68

0.6900000000000001

0.7000000000000001

0.7100000000000001

0.7200000000000001

0.7300000000000001

0.7400000000000001

where did 0.0000000000000001 come from?

thanks a lot!

WangGang
  • 533
  • 3
  • 15
karl00222
  • 21
  • 2
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – MisterMiyagi Mar 13 '20 at 05:48

1 Answers1

2

This questioned has been answered before here. In summary, it has to do with how values are stored, so 0.1 is actually stored as exactly 0.1000000000000000055511151231257827021181583404541015625 hence why you get the extra 1 at the end. You can look more into by clicking on the link. To solve this problem, you can use the built-in round function. Like so:

start = 0.65

end = 0.75

step = 0.01

while start <= end:

    print (start)

    start = round(start + step, 2) # this rounds the answer to the nearest hundredth

Hope this helped!

WangGang
  • 533
  • 3
  • 15