[Python] Replicating C Fixed-Point Math in Python

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to replicate a DSP algorithm in Python that was originally written in C. The trick is I also need to retain the same behavior of the 32 bit fixed point variables from the C version, including any numerical errors that the limited precision would introduce.

    The current options I think are available are:

    I know the python Decimal type can be used for fixed-point arithmetic, however from what I can tell there is no way to adjust the size of a Decimal variable. To my knowledge numpy does not support doing fixed point operations.

    I did a quick experiment to see how fiddling with the Decimal precision affected things:

    >>> a = dc.Decimal(1.1)
    >>> a
    Decimal('1.100000000000000088817841970012523233890533447265625')
    >>> sys.getsizeof(a)
    104
    >>> dc.getcontext().prec = 16
    >>> a = dc.Decimal(1.1)
    >>> a
    Decimal('1.1999999999999999555910790149937383830547332763671875')
    >>> sys.getsizeof(a)
    104


    There is a change before/after the precision change, however there are still a large number of decimal places. The variable is still the same size, and has quite a few decimal places after it.

    How can I best go about achieving the original objective? I do know that Python ctypes has the C language float, but I do not know if that will be useful in this case. I do not know if there is even a way to accurately mimic C type fixed point math in Python.

    Thanks!

    Continue reading...

Compartilhe esta Página