francof2a / fxpmath

A python library for fractional fixed-point (base 2) arithmetic and binary manipulation with Numpy compatibility.
MIT License
179 stars 21 forks source link

Powers take too long #57

Closed deescuderoo closed 2 years ago

deescuderoo commented 2 years ago

For my application I need to compute multiple powers. However, it seems that for certain amounts of fractional bits n_frac, powers take too long to compute. For example:

from fxpmath import Fxp

k = 30

e = 10
x = Fxp(1, signed=True, n_word=k, n_frac=e)
z = x ** 1 # Takes about 1s

e = 15
x = Fxp(1, signed=True, n_word=k, n_frac=e)
z = x ** 1 # Never finishes

Why is this? One would expect powers to be relatively fast, specially one as x ** 1.

Any advice on this would be very useful, I don't want to redefine the method. Thanks!

francof2a commented 2 years ago

Hello,

By default, when you do a operation between a Fxp and a constant, that constant is casted to a same Fxp type. So, going deep in details, you are not performing a power of 1 but a power with 1 * 2**10 under the hood. Fxpmath is trying to calculate in fixed point, so that calculation is time demanding.

If you don't to emulate a fixed point power with that precision, try:

z = x ** Fxp(1) # Fxp(1) create a fixed point with enough precision -> n_frac = 0

There is another way, calculate in floating point under the hood, but this doesn't emulate fixed point precision.

deescuderoo commented 2 years ago

Thank you @francof2a.

I will need to evaluate polynomials using fixed-point inputs, for which I will need powers. I literally need x ** k to perform x * x * ... * x, k times. I tried your solution and it indeed works, or at least it seems faster. I will use that for now and let you know if I have any other concern.

Thanks for the nice work!

francof2a commented 2 years ago

Thanks for the feedback. Closing the issue! Do not hesitate to ask if you have any questions