Python 测试两个浮点数是否在1 ULP内
如何确定两个浮点数之间的差值是否最多为1 ULP 类似于下面的代码,它(忽略符号和指数)提取尾数的二进制,但稍微不那么可怕:Python 测试两个浮点数是否在1 ULP内,python,floating-point,Python,Floating Point,如何确定两个浮点数之间的差值是否最多为1 ULP 类似于下面的代码,它(忽略符号和指数)提取尾数的二进制,但稍微不那么可怕: 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('+'
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
a=int(.hex().lstrip('-').lstrip('0x')[1:].lstrip('.')[:-3].rstrip('+').rstrip('p'),16)
b=int(.hex().lstrip('-').lstrip('0x')[1:][.lstrip('.')[:-3].rstrip('+').rstrip('p'),16)
使用NumPy打印abs(a-b),您可以获得给定数字后的下一个浮点数:
# 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)
(例如,如果两个数字具有不同的ULP,或者如果其中一个是无穷大,这可能不是您想要的。)如果“两个数字具有不同的ULP”,为什么会出现问题?非常感谢您的回答,但我更愿意只使用Python stdlib,而不是NumPy…@EcirHana:如果a和b彼此在一个a-ULP范围内,而不是在一个b-ULP范围内,会发生什么?这张支票是假的。也许你不想那样,我明白了。在这种情况下,我的问题是错误的,你的答案是正确的:)。当他们的ULP不同意时,没有问题。如果有两个可表示的数字之间没有其他数字,则其中一个必须是2的幂。