0

I came across a equality comparison problem in python 2.7. I ran the following program,expecting that elist[i][1] == MC will return True.

elist=elist=[[1,1],[2,4],[3,9]]
MC=0
while (MC<1.01):
    MC+=0.01
    for i in range(len(elist)):
        #test equality
        print elist[i][1]
        print MC
        print elist[i][1]==int(MC)

But it came out as:

1
1.0
False
4
1.0
False
9
1.0
False

Even I change into:

float(elist[i][1])==float(MC)

It still returns the same result.

Does anybody know why this happen?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99

1 Answers1

0

This is due to the way that most computers handle floating point numbers. 0.1 is an irrational binary number, like 1/3 is in decimal. A simpler demonstration is print(0.1+0.1+0.1) which prints 0.30000000000000004. That number would be seen as different to to 0.3 if I compare with ==. You should compare for almost-equality in this case, as noted in the comment above.

Galax
  • 1,441
  • 7
  • 6