Number of floats between two floats

后端 未结 4 1918
一整个雨季
一整个雨季 2021-02-20 03:41

Say I have two Python floats a and b, is there an easy way to find out how many representable real numbers are between the two in IEEE-754 representati

4条回答
  •  囚心锁ツ
    2021-02-20 04:08

    I would look at the frexp function in the math module. The example below extracts the mantissa and converts it to an integer. The difference should be the number of floats between to the two values.

    >>> math.frexp(1.1234567890)[0] * 2**53
    5059599576307254.0
    >>> math.frexp(1.12345678901)[0] * 2**53
    5059599576352290.0
    

    The following code should do it:

    import math
    import sys
    
    def delta(x,y):
        '''Return the number of floats between x and y.'''
        x = float(x)
        y = float(y)
        if x == y:
            return 0
        elif x < y:
            return -delta(y,x)
        else:
            x_mant, x_exp = math.frexp(x)
            y_mant, y_exp = math.frexp(y)
            x_int = int(x_mant * 2**(sys.float_info.mant_dig + x_exp - y_exp))
            y_int = int(y_mant * 2**sys.float_info.mant_dig)
            return x_int - y_int
    
    print(delta(1.123456789, 1.1234567889999))
    450
    >>>
    

提交回复
热议问题