Number of floats between two floats

后端 未结 4 1919
一整个雨季
一整个雨季 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 03:44

    I don'tknow what you will be using this for - but, if both floats have the same exponent, it should be possible. As the exponent is kept on the high order bits, loading the float bytes (8 bytes in this case) as an integer and subtracting one from another should give the number you want. I use the struct model to pack the floats to a binary representation, and then unpack those as (C, 8 byte) long ints:

    >>> import struct
    >>> a = struct.pack("dd", 1.000000,1.000001)
    >>> b = struct.unpack("ll",a)
    >>> b[1] - b[0]
    4503599627
    >>> a = struct.pack("dd", 1.000000000,1.000000001)
    >>> b = struct.unpack("ll",a)
    >>> b[1] - b[0]
    4503600
    >>>
    

提交回复
热议问题