simple float numbers problem

Fredrik Lundh fredrik at pythonware.com
Fri Nov 7 11:50:16 EST 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.

that's how floating point numbers work.  see:

 http://www.python.org/doc/current/tut/node14.html

> Perhaps because Python translates "25.99" to "25.98999999999999998" and
> not "25.99", which may be the reason for this error (me guessing...). If
> that's the case, how do I force Python to only use 2 decimal points, and
> not "make up" superfluous decimals? 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)?

convert both terms to strings, and compare the strings.

or calculate the absolute value of the difference between the two
numbers (abs(x-y)) and compare that to a small constant.

or use a data type designed to handle decimal numbers, such as:

    http://fixedpoint.sourceforge.net/

</F>








More information about the Python-list mailing list