simple float numbers problem
Bengt Richter
bokr at oz.net
Sat Nov 8 19:46:00 EST 2003
On Fri, 7 Nov 2003 17:50:16 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:
>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.
>
With exact decimals you can do it:
>>> from exactdec import ED
>>> ED(10)+ED('15.99') == ED('25.99')
True
but if I get all the bits from floating point values instead of exactly interpreting string literals,
we can see what happened to you:
>>> print '%s\n%s'%(ED(10+15.99, 'all'), ED(25.99,'all'))
ED('25.99000000000000198951966012828052043914794921875')
ED('25.989999999999998436805981327779591083526611328125')
Grabbing less bits:
>>> print '%s\n%s'%(ED(10+15.99, 15), ED(25.99, 15))
ED('25.990000000000002')
ED('25.989999999999998')
15 fractional decimals still shows a difference, but
>>> print '%s\n%s'%(ED(10+15.99, 14), ED(25.99, 14))
ED('25.99')
ED('25.99')
So we can expect
>>> ED(10+15.99, 14) == ED(25.99, 14)
True
>that's how floating point numbers work. see:
>
> http://www.python.org/doc/current/tut/node14.html
>
Or play with the new toy. I posted it to the "prePEP: Decimal data type" thread ;-)
>> 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/
>
Still, note the difference beween enforcing rounding to a number of fractional bits
as you go (maybe it doesn't do that??) vs keeping exactness until rounding is explicitly
invoked by a method or during construction from another value.
Also note that exact values can be expensive (time, space) to keep, because there is
a kind of rational type hiding in there ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list