Search code examples
pythonbinaryfloating-pointbitstringmpmath

How to input a float as a string of '0' and '1' characters with the bitstring package?


I want to use the packages bitstring and mpmath (or any other way to guarantee an arbitrarily set output precision and specified rounding mode) to calculate values of rcp, sqrt, sin, cos, ln, exp,... on float inputs given as binary bitstrings and get a binary bitstring answer.

My go-to for this is MPFR in C, but I want to explore Python's floating point high-precision packages, hoping for easier handling. My first problem is how to reverse the following decimal float to bitstring conversion:

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

i.e. how to feed '00111111100110011001100110011010' to either bitstring or mpmath in a way that it interprets it as (just over) 1.2 and then feed that to a function such as sin, cos, or ln (turning my answer into a bitstring again).

I'm finding it hard to learn about binary input from the Python bitstring/mpmath documentation. It only says about the difficulties of decimal float representation, but not how to bypass these simply inputting exact binary floats.


Solution

  • BitArray takes the bin parameter, which initialises it from a binary string representation:

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

    So a general function to do this:

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