1
votes

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!

1
C fixed point math: Isn't this simply calculating with integral types under the assumption that one increment represents a possible fractional value of a certain physical quantity? (E.g. +1 => +0.012 V) This in mind, I don't see the problem to do this in Python as well. - Scheff's Cat
I believe my impression was not that bad: SO: Fixed Point Arithmetic in C Programming. ;-) - Scheff's Cat
@Scheff Yes, fixed-point arithmetic is essentially calculating with integer types, but it is required that the bit-width of the variables be known and unchanging. As I understand it, the OP is looking for a way to explicitly control the bit-width of the variables. - Elliot Alderson
Pretty much. If it came down to it I could write my own type which would do the job manually, but I was hoping there was something pre-existing that I could use to do the job. - alphasierra

1 Answers

0
votes

I recommend fxpmath module for fixed-point operations in python. Maybe with that you can emulate the fixed point arithmetic defining precision in bits (fractional part). It supports arrays and some arithmetic operations.

Repo at: https://github.com/francof2a/fxpmath

Here an example:

from fxpmath import Fxp

x = Fxp(1.1, True, 32, 16)   # (val, signed, n_word, n_frac)

print(x)
print(x.precision)

results in:

1.0999908447265625
1.52587890625e-05