Precision for equality of two floats?

Bengt Richter bokr at oz.net
Tue Nov 29 09:31:46 EST 2005


On Mon, 28 Nov 2005 07:58:37 -0800, aleax at mail.comcast.net (Alex Martelli) wrote:

>Anton81 <berrybear at gmx.net> wrote:
>
>> Hi!
>> 
>> When I do simple calculation with float values, they are rarely exactly
>> equal even if they should be. What is the threshold and how can I change
>> it?
>
>Python's builtin floats compare for exact bit-by-bit equality -- no
>"threshold".  You may want to look at the allclose function in the
Does "exact bit-by-bit" mean that

    a = <floatexpr>
    a == <floatexpr>

is 100% guaranteed? I.e., are there implementations where an expression
value might remain in 80-bit representation in the fpu and be rounded
to 64 bits for assignment to a and then not compare equal because the second
a is a rounded 64-bit value compared to the regenerated 80-bit value?

Since cpython bytecodes store expression values on the cpu stack, not
the fpu stack, I assume it's ok there, but is it a potential problem
for optimizers generating machine code? Or is it spec-ed for mandatory
as-if-storing-both-arguments-as-double-before-comparing behaviour?

Just wondering ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list