【问题标题】:Extracting floating-point significand and exponent in NumPy在 NumPy 中提取浮点有效数和指数
【发布时间】:2018-02-16 00:02:15
【问题描述】:

我希望能够在 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'

以这种方式提取指数和符号并不方便,因为bin 去掉了前导 0。 (不过我可以用 0 填充到 32 位……)

无论如何,因为bin 不是ufunc,这不方便,我必须遍历数组。

没有更方便的方法来做我想做的事吗?

【问题讨论】:

  • 看看this answer,它可能会为你指明正确的方向
  • @GPhilo:谢谢。实际上,这个答案似乎清楚地表明,不,没有更方便的方法。
  • 看看numpy.frexp
  • @MarkDickinson: numpy.frexpa 分解为指数和 尾数,而不是将 分解为指数和 significand 以 IEEE 754 浮点数编码。 (frexp 给出的指数与 IEEE 754 浮点指数相差 1。)
  • @equaeghe:是的,但是从frexp 结果到 IEEE 754 分解是微不足道的。正如您所说,指数相差 1,因此从指数中减去 1 并将有效数加倍。

标签: python numpy floating-point exponent significant-digits


【解决方案1】:

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)

这种对整数进行位级运算的方法实际上比转到实际的位串本身更方便。

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2014-11-23
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多