我希望能够在 NumPy 中提取 float 的有效数和指数。将指数作为整数获取是可以的,并且对于有效数来说也是可以的。将有效数作为位域获取会更加方便。
我知道Python float 有一个hex
方法;但是,我希望使用 numpy.float32、numpy 数组和 ufunc。我还知道 numpy view
方法允许我将 float 视为整数,从而将其视为二进制字符串:
>>> import numpy as np
>>> b = bin(np.float32(1.23456789).view(np.int32))
'0b111111100111100000011001010010'
>>> b[-23:] # extract last 23 bits of IEEE 754 binary32 float, is significand
'00111100000011001010010'
以这种方式提取指数和符号并不方便,因为 bin
会删除前导 0。 (不过我可以用 0 左填充到 32 位……)
无论如何,因为 bin
不是 ufunc,这并不方便,我必须迭代该数组。
没有更方便的方法来做我想做的事吗?
最佳答案
GPhilio 的评论引发了对 SO 的更彻底的搜索,基于 an answer to “extracting mantissa and exponent from double in c#” 得出了以下解决方案:
import numpy as np
def decompose(x: np.float32):
"""decomposes a float32 into negative, exponent, and significand"""
negative = x < 0
n = np.abs(x).view(np.int32) # discard sign (MSB now 0),
# view bit string as int32
exponent = (n >> 23) - 127 # drop significand, correct exponent offset
# 23 and 127 are specific to float32
significand = n & np.int32(2**23 - 1) # second factor provides mask
# to extract significand
return (negative, exponent, significand)
这种对整数进行位级操作的方法实际上比实际的位串本身更方便。
关于python - 在 NumPy 中提取浮点有效数和指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46093123/