2

I am a beginner to python and was wondering why the code spans for infinity when it should've been stopped at 1.

def main():
    i = 0.0
    while i != 1.0:
        print("i =", i)
        i += 0.1
main()

2 Answers2

3

This is a well known problem in Python.

Your variable i never becomes exactly 1, but instead becomes 0.9999999999999999.

Do instead:

def main():
    i = 0.0
    while i <= 1.0:
        print("i =", i)
        i += 0.1
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
  • 3
    I would not call it a problem with python, rather a problem with binary representations of decimal numbers. – timgeb Mar 19 '17 at 17:38
  • i = 0.0 i = 0.1 i = 0.2 i = 0.30000000000000004 i = 0.4 i = 0.5 i = 0.6 i = 0.7 i = 0.7999999999999999 i = 0.8999999999999999 i = 0.9999999999999999 –  Mar 19 '17 at 17:40
  • You asked why it acts as it does, not how to correct it. I am, however, happy to oblige: replace `i += 0.1` with `i = round(i+0.1, 1)` – stelioslogothetis Mar 19 '17 at 17:43
  • Thanks..Sorry if I sounded rude. –  Mar 19 '17 at 17:49
1

In the general case, of course you shouldn't compare floats by equality, but there's more to it: when you're adding like this you get floating point accumulation error.

You can use an integer counter instead and apply multiplication every time to avoid that.

def main():
    i = 0.0
    count = 0
    while i < 1.0:
        print("i =", i)
        count += 1
        i = count*0.1

main()

I have replaced i != 1.0 by i < 1.0 because that's all you need, but it even works with != (although I don't recommend that) now because there's no accumulation error anymore the way it's computed with the integer counter.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219