在 NumPy 中提取浮点有效数和指数
Extracting floating-point significand and exponent in NumPy
我希望能够在 NumPy 中提取浮点数的尾数和指数。将指数作为整数很好,对于尾数也可以。将有效数字作为位域会更加方便。
我知道 Python 花车有一个 hex
方法;但是,我希望使用 numpy.float32
、numpy 数组和 ufunc。我也知道 numpy view
方法允许我将浮点数视为整数,从而将其视为二进制字符串:
>>> 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'
以这种方式提取指数和符号并不方便,因为前导 0 被 bin
删除了。 (虽然我可以用 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)
这种对整数进行位级运算的方法实际上比对实际位串本身更方便。
我希望能够在 NumPy 中提取浮点数的尾数和指数。将指数作为整数很好,对于尾数也可以。将有效数字作为位域会更加方便。
我知道 Python 花车有一个 hex
方法;但是,我希望使用 numpy.float32
、numpy 数组和 ufunc。我也知道 numpy view
方法允许我将浮点数视为整数,从而将其视为二进制字符串:
>>> 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'
以这种方式提取指数和符号并不方便,因为前导 0 被 bin
删除了。 (虽然我可以用 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)
这种对整数进行位级运算的方法实际上比对实际位串本身更方便。