0

There is a python code as following:

import sys
import fileinput, string
K = 3
f = raw_input("please input the initial "+str(K)+" lamba: ").split()

Z = []
sumoflamba = 0.0
for m in f:
    j = m.find("/")
    if j!=-1:
            e=float(m[:j])/float(m[j+1:])
    else:
            e = float(m)
    sumoflamba+=e
    if e==0:
            print "the initial lamba cannot be zero!"
            sys.exit()
    Z.append(e)
print sumoflamba
if sumoflamba!=1:
    print "initial lamba must be summed to 1!"
    sys.exit()

When I run it with 0.7, 0.2, 0.1. It will print the warning and exits! However, when I run it with 0.1, 0.2, 0.7. It works fine. 0.3, 0.3, 0.4 works fine too. I do not have a clue....Can someone explain this, please? The "print sumoflamda" will give 1.0 for all these cases.

Haohan Wang
  • 607
  • 2
  • 9
  • 25
  • 2
    [Obligatory link.](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Gareth Latty Feb 18 '13 at 01:14
  • Lattyware's link holds the answer, I think. To illustrate the problem more compactly, try running `.7+.2+.1` in a Python interpreter. – Blckknght Feb 18 '13 at 01:18
  • 3
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html) – Ken White Feb 18 '13 at 01:18
  • This is a duplicate of so many questions on Stack Overflow it's not even funny. – John Y Feb 18 '13 at 01:29

3 Answers3

5

Pretty much what the link Lattyware provided explains - but in a nutshell, you can't expect equality comparisons to work in floating point without being explicit about the precision. If you were to either round off the value or cast it to an integer you would get predictable results

>>> f1 = 0.7 + 0.2 + 0.1
>>> f2 = 0.1 + 0.2 + 0.7
>>> f1 == f2
False
>>> round(f1,2) == round(f2,2)
True
Ali-Akber Saifee
  • 4,406
  • 1
  • 16
  • 18
0

Floats are imprecise. The more you operate with them, the more imprecision they accumulate. Some numbers can be represented exactly, but most cannot. Comparing them for equality will almost always be a mistake.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
0

It is a bad practice to check floating point numbers for equality. Best you can do here is to check that your number within the desired range. For details of how floating point works see http://en.wikipedia.org/wiki/Floating_point#Internal_representation

Sergey
  • 627
  • 1
  • 9
  • 16