简体   繁体   English

将浮点数转换为定点数

[英]Convert floating point to fixed point

I want to convert floating point sin values to fixed point values.我想将浮点 sin 值转换为定点值。

import numpy as np

Fs = 8000
f = 5
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)

How can I easily convert this y floating point samples to fixed point samples?如何轻松地将此y浮点样本转换为定点样本?

Each element should be of 16bit and 1 bit integer part and 15 bits should be of fractional part, so that I can pass these samples to a DAC chip.每个元素应该是 16 位和 1 位整数部分,15 位应该是小数部分,以便我可以将这些样本传递给 DAC 芯片。

To convert the samples from float to Q1.15 , multiply the samples by 2 ** 15 .要将样本从float转换为Q1.15 ,请将样本乘以2 ** 15 However, as mentioned in the comments, you can't represent 1.0 in Q1.15 , since the LSB is representing the sign.但是,如评论中所述,您不能在Q1.15表示1.0 ,因为 LSB 表示符号。 Therefore you should clamp your values in the range of [-1, MAX_Q1_15] where MAX_Q1_15 = 1.0 - (2 ** -15) .因此,您应该将值限制在[-1, MAX_Q1_15]范围内,其中MAX_Q1_15 = 1.0 - (2 ** -15) This can be done with a few helpful numpy functions.这可以通过一些有用的 numpy 函数来完成。

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.尽管您可能担心这种表示不能准确表示1.0的值,但它足以进行计算。 For example, if you were to square 1.0 :例如,如果您要平方1.0

fmul_16x16 = lambda x, y: x * y >> 15
fmul_16x16(32767, 32767) # Result --> 32766

Which is very close, with 1-bit error.这是非常接近的,有 1 位错误。

Hopefully it helps.希望它有帮助。

You can use fxpmath to convert float values to fractional fixed-point.您可以使用fxpmath将浮点值转换为小数定点。 It supports Numpy arrays as inputs, so:它支持 Numpy 数组作为输入,因此:

from fxpmath import Fxp

# your example code here

y_fxp = Fxp(y, signed=True, n_word=16, n_frac=15)

# plotting code here

eQ16.15

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:小数的 15 位为您提供了非常低的幅度分辨率值,因此我绘制 Q5.4 以夸张的方式显示转换:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM