simple float numbers problem

Tim Roberts timr at probo.com
Sun Nov 9 09:10:14 CET 2003


Vio <vmilitaru at sympatico.ca> wrote:
>
>I need to test for equality between simple 2 decimal numbers. For example:
>
>if (10 + 15.99) == 25.99:
>       do some stuff...
>
>The preceding sentence should be TRUE, but to Python it appears FALSE. 
>Which is wrong.

And the same thing would happen if you wrote the same sentence in C.  The
problem is that 15.99 in binary is an infinitely repeating decimal.  It
cannot be represented exactly.

>If that's the case, how do I force Python to only use 2 decimal points, 
>and not "make up" superfluous decimals? 

There are two good solutions.  One, as others have suggested, is to store
everything in units of cents.  Your expression becomes:

    if 1000 + 1599 == 2599:
         do some stuff...

All you need to do is translate when you do input and output.  This is the
approach Visual Basic takes with its Currency data type (although it
actually multiples by 1000, not 100).

Another solution is to use a "CloseTo" function to do the comparison:

  def CloseTo(x,y):
      return abs(x-y) < 0.005

  if (10.00 + 15.99, 25.99):
     do some thuff...

>Or if that's not the cause for the problem, how do I make 
>Python see my math expression as TRUE (as it "should" be)?

In a binary computer, your statement is false.  Just that simple.  You need
to find a way to express your statement in a way that produces the results
you want.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.




More information about the Python-list mailing list