0

I have written a small python program which gets stuck in a loop for reasons unknown to me.

This is my code:

a = 0
b = 1
step = 0.1

while True:
    if a == b:
        print 'exit'
        break
    if a < b:
        a += step
        print a
    if a > b:
        a -= step
        print a

This is the output:

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.0
1.1
1.0
[...]

Why doesn't the loop terminate, but even yield values larger than 1?

EDIT:

I've done it now with the decimal module:

from decimal import *

getcontext().prec = 1

a = 0
b = 1
step = Decimal('0.1')

while True:
    if a == b:
        print 'exit'
        break
    if a < b:
        a += step
        print a
    if a > b:
        a -= step
        print a

1 Answers1

1

Your should never check equality of floating point values. Best way is to use constraint on error.

if abs(a - b) <= allowed_error :
    do something
Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66