Search code examples
pythonpython-3.xcompareequalitylargenumber

Why do comparisions between very large float values fail in python?


In my understanding, sys.float_info.max is the largest possible float value. However, it seems that comparing such large values fail.

import math
import sys

m = sys.float_info.max                        # type 'float'

m == m                                        # True
m < m                                         # False
m > m                                         # False

m == m-1.0                                    # True
m < m-1.0                                     # False
m > m-1.0                                     # False

m == m-1e100                                  # True
m < m-1e100                                   # False
m > m-1e100                                   # False

m == m-1e300                                  # False
m > m-1e300                                   # True
m < m-1e300                                   # False

I assume that's because of the limited precision? If so, in what numerical range can i operate safely?

The above code was run with Python 3.5.2.


Solution

  • On a typical machine running Python, there are 53 bits of precision available for a Python float. If you try to go further, Python will eliminate the smallest part so the number can be properly represented.

    So the value 1 is absorbed or cancelled to be able to represent the high value you're trying to compute.

    The limit is obtained by subtracting (or adding) the value multiplied by float epsilon.

    On my machine:

    maxfloat == 1.7976931348623157e+308
    epsilon == 2.220446049250313e-16
    

    sample test code

    import math
    import sys
    
    m = sys.float_info.max                        # type 'float'
    eps = sys.float_info.epsilon
    
    print(m == m-(m*(eps/10)))   # True
    print(m == m-(m*eps))        # False
    

    m*eps is the smallest value you have to subtract to make comparison fail. It's always relative to the m value.