Created
July 22, 2020 02:46
-
-
Save rldotai/1f3537608c2cb707c208c5e82a9c3456 to your computer and use it in GitHub Desktop.
Calculate the number of distinct floats between two numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Calculate the number of distinct floats between two numbers via bit packing and | |
unpacking. | |
-------------------------------------------------------------------------------- | |
>>> distinct_floats(1, 0) | |
4607182418800017408 | |
>>> distinct_floats(-1, 0) | |
4616189618054758400 | |
>>> distinct_floats(0, float('inf')) | |
9218868437227405312 | |
# When the inputs are of opposite sign, the results stop making sense because the | |
# unpacked values hit the limits of what can be represented as a long integer. | |
>>> distinct_floats(-1, 1) | |
9223372036854775808 | |
>>> distinct_floats(float('inf'), float('-inf')) | |
9223372036854775808 | |
>>> np.iinfo(np.int) | |
iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64) | |
""" | |
import struct | |
import numpy as np | |
def distinct_floats(a, b): | |
"""Return the number of distinct floats between `a` and `b`""" | |
# Handle the case where inputs have opposite signs | |
if np.sign(a)*np.sign(b) == -1: | |
return float_range(a, 0) + float_range(b, 0) | |
else: | |
tmp = struct.pack('dd', a, b) | |
res = struct.unpack('ll', tmp) | |
return abs(res[1] - res[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment