如何将一个浮点数输入为' 0'和' 1' bitstring包的字符?

时间:2017-06-15 16:18:51

标签: python binary floating-point bitstring mpmath

我想使用包bitstringmpmath(或任何其他方式来保证任意设置的输出精度和指定的舍入模式)来计算rcp的值,{{1 }},sqrtsin s,coln,...在以二进制exp s形式给出的浮点输入上获取二进制{{1回答。

我的目标是C中的MPFR,但我想探索Python的浮点高精度软件包,希望更容易处理。我的第一个问题是如何将以下十进制浮点数反转为bitstring转换:

bitstring

即。如何将bitstring提供给>>> from bitstring import * >>> a = BitArray(float=1.2,length=32) >>> a.bin '00111111100110011001100110011010' '00111111100110011001100110011010',方式是将其解释为(刚刚结束)bitstring,然后将其提供给{{1}等函数}},mpmath1.2(将我的答案再次转换为sin)。

我发现很难从Python cos / ln文档中了解二进制输入。它只说十进制浮点表示的困难,而不是如何绕过这些只是输入精确的二进制浮点数。

2 个答案:

答案 0 :(得分:2)

根据BitArray doc字符串,您可以指定bin参数:

__init__(self, auto=None, length=None, offset=None, **kwargs)
    Either specify an 'auto' initialiser:
    auto -- a string of comma separated tokens, an integer, a file object,
            a bytearray, a boolean iterable or another bitstring.

    Or initialise via **kwargs with one (and only one) of:
    bytes -- raw data as a string, for example read from a binary file.
    bin -- binary string representation, e.g. '0b001010'.   <--------------
    hex -- hexadecimal string representation, e.g. '0x2ef'
    oct -- octal string representation, e.g. '0o777'.
    uint -- an unsigned integer.
    int -- a signed integer.
    float -- a floating point number.
    uintbe -- an unsigned big-endian whole byte integer.
    intbe -- a signed big-endian whole byte integer.
    floatbe - a big-endian floating point number.
    uintle -- an unsigned little-endian whole byte integer.
    intle -- a signed little-endian whole byte integer.
    floatle -- a little-endian floating point number.
    uintne -- an unsigned native-endian whole byte integer.
    intne -- a signed native-endian whole byte integer.
    floatne -- a native-endian floating point number.
    se -- a signed exponential-Golomb code.
    ue -- an unsigned exponential-Golomb code.
    sie -- a signed interleaved exponential-Golomb code.
    uie -- an unsigned interleaved exponential-Golomb code.
    bool -- a boolean (True or False).
    filename -- a file which will be opened in binary read-only mode.

    Other keyword arguments:
    length -- length of the bitstring in bits, if needed and appropriate.
              It must be supplied for all integer and float initialisers.
    offset -- bit offset to the data. These offset bits are
              ignored and this is intended for use when
              initialising using 'bytes' or 'filename'.
>>> a = BitArray(bin='00111111100110011001100110011010')
>>> a.bin
'00111111100110011001100110011010'

使用float属性获取浮点值:

>>> a.float
1.2000000476837158
>>> 

答案 1 :(得分:2)

BitArray获取bin参数,该参数从二进制字符串表示中初始化它:

>>> from bitstring import *
>>> a = BitArray(float=1.2, length=32)
>>> a.bin
'00111111100110011001100110011010'
>>> b = BitArray(bin=a.bin)
>>> b.float
1.2000000476837158

这是执行此操作的一般功能:

def float_from_bitstring(bitstring):
    return BitArray(bin=bitstring).float