我希望能够在NumPy中提取浮点数的意义和指数.得到指数作为一个整数是很好和可以的意义。得到这个意义,作为一个位域,就更容易了。
我知道Python有一个hex
方法;但是,我希望使用numpy.float32
、numpy数组和use。我还知道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'
用这种方法提取指数和符号是不方便的,因为bin
删除了前导0。(通过…,我可以从0到32位。)
在任何情况下,因为bin
不是ufunc,这不方便,因此我必须遍历数组。
没有更方便的方法来做我想做的事了吗?
发布于 2017-09-07 05:51:38
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)
这种对整数进行位级操作的方法实际上比实际的位字符串本身更方便。
https://stackoverflow.com/questions/46093123
复制相似问题