2017-06-15 98 views
1

我要使用的封裝bitstringmpmath(或任何其他方式來保證任意設定的輸出精度和指定舍入模式)來計算的rcpsqrtsinco S,lnexp值,...上浮動輸入以二進制形式給出bitstring s並得到一個二進制bitstring答案。如何使用bitstring包作爲「0」和「1」字符的字符串輸入float?

我的目標是C語言中的MPFR,但我想探索Python的浮點高精度包,希望能夠更輕鬆地處理。我的第一個問題是如何將以下十進制浮點相反bitstring轉換:

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

即如何以一種方式進料'00111111100110011001100110011010'要麼bitstringmpmath,它會將其解釋爲(剛剛超過)1.2再喂,爲了一個函數,如sincosln(將我的答案再次轉換爲bitstring)。

我發現很難從Python bitstring/mpmath文檔中瞭解二進制輸入。它只是說十進制浮點數表達式的困難,而不是如何繞過這些簡單輸入精確的二進制浮點數。

回答

2

BitArray採取bin參數,在哪從二進制字符串表示itialises它:

>>> 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 
2

根據BitArray文檔字符串,可以指定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 
>>> 
相關問題