Reputation: 11508
How to find out whether the difference between two floating-point numbers is at most 1 ULP?
Something like the code below, which (ignores the signs and exponent, and) extracts the binary of mantissa, but slightly less awful:
a = int(<float>.hex().lstrip('-').lstrip('0x')[1:].lstrip('.')[:-3].rstrip('+').rstrip('p'), 16)
b = int(<float>.hex().lstrip('-').lstrip('0x')[1:].lstrip('.')[:-3].rstrip('+').rstrip('p'), 16)
print abs(a - b) <= 1
Upvotes: 2
Views: 1516
Reputation: 281594
With NumPy, you can get the next floating-point number after a given number:
# Test whether taking the smallest possible step from b in the direction of a gets you a.
# Special case: If b == a, then np.nextafter(b, a) == a
a == np.nextafter(b, a)
(This might not quite be what you want if, say, the two numbers have different ULPs, or if one is an infinity.)
Upvotes: 1