Skip to content

Instantly share code, notes, and snippets.

@rldotai
Created July 22, 2020 02:46
Show Gist options
  • Save rldotai/1f3537608c2cb707c208c5e82a9c3456 to your computer and use it in GitHub Desktop.
Save rldotai/1f3537608c2cb707c208c5e82a9c3456 to your computer and use it in GitHub Desktop.
Calculate the number of distinct floats between two numbers.
"""
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