pythonfloating-pointprecision

Does equality check for floats in python check against machine epsilon tolerances?


I'm a bit confused about the precision on floats in python and equality checks.

e.g.,

15 + 1e-16 == 15

evaluates to true b/c 1e-16 is < machine epsilon for fp64.

and

15 + 1e-15 == 15

evaluates false because 1e-15 > machine epsilon for fp64.

But when I do sys.getsizeof(15 + 1e-16), I get 24 bytes, i.e., fp192, which if it were true, would mean 15 + 1e-16 == 15 would evaluate false since machine epsilon for fp192 is surely << 1e-16.

I always thought == is checking whether the LHS is within +/- of machine epsilon for the respective type.

To add to my confusion, I checked:

1e-323 == 0 # evaluates false
1e-324 == 0 # evaluates true
sys.getsizeof(1e-323) # gives 24 bytes

I don't understand the bound on this.


Solution

  • Comparison of all numeric types (including floats) is exact in Python. Hardware precision has nothing to do with it.

    getsizeof() is returning the size of the Python object, which includes things like bytes for a pointer to the object's type object, and the reference count. The actual data for a float occupies 8 bytes on almost all current machines, a small part of it.