Convert Floating Point To Fixed Point
Solution 1:
To convert the samples from float
to Q1.15
, multiply the samples by 2 ** 15
. However, as mentioned in the comments, you can't represent 1.0
in Q1.15
, since the LSB is representing the sign. Therefore you should clamp your values in the range of [-1, MAX_Q1_15]
where MAX_Q1_15 = 1.0 - (2 ** -15)
. This can be done with a few helpful numpy functions.
y_clamped = np.clip(y, -1.0, float.fromhex("0x0.fffe"))
y_fixed = np.multiply(y_clamped, 32768).astype(np.int16)
Although you may fear this representation does not accurately represent the value of 1.0
, it is close enough to do computation with. For example, if you were to square 1.0
:
fmul_16x16 = lambda x, y: x * y >> 15
fmul_16x16(32767, 32767) # Result --> 32766
Which is very close, with 1-bit error.
Hopefully it helps.
Solution 2:
You can use fxpmath to convert float values to fractional fixed-point. It supports Numpy arrays as inputs, so:
from fxpmath import Fxp
# your example code here
y_fxp = Fxp(y, signed=True, n_word=16, n_frac=15)
# plotting code here
15 bits for fractional give you a very low value for amplitue resolution, so I plot Q5.4 to show the conversion in an exaggerated way:
Post a Comment for "Convert Floating Point To Fixed Point"