francof2a / fxpmath

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

Bug: Inaccuracy for certain complex multiplications #91

Open MaxWipfli opened 9 months ago

MaxWipfli commented 9 months ago

When performing multiplications using complex Fxp numbers, the result dtype is not inferred correctly. This can lead to overflow in the resulting value.

Example:

from fxpmath import Fxp
x = Fxp(-1-1j)
x.info()
# dtype     =   fxp-s1/0-complex
# Value     =   (-1-1j)

y = x * x

y.info()
# dtype     =   fxp-s2/0-complex
# Value     =   1j
# overflow  =   True
# inaccuracy    =   True

As shown above, the result is y = 1j, even though the correct result would be y = 2j, which cannot be represented by dtype = fxp-s2/0-complex.

I suspect the bug is that the inference of the result dtype misses the fact that a complex multiplication also requires an addition/subtraction, requiring another bit to represent the values accurately:

(a + j * b) * (c + j * d) = (ac - bd) + j * (ad + bc)

I am using fxpmath version 0.4.8, installed from PyPI.

francof2a commented 9 months ago

I could reproduce the bug. Yor're right about an extra bit is necessary because additions/subtractions.

This will be fixed in version 0.4.10. Thanks!