我目前正在尝试找出如何以定点表示形式将两个数字相乘。
假设我的数字表示如下:
[SIGN][2^0].[2^-1][2^-2]..[2^-14]
就我而言,数量10.01000000000000 = -0.25
.
例如我会怎么做0.25x0.25
or -0.25x0.25
etc?
希望您能帮忙!
You should use 2's complement representation instead of a seperate sign bit https://en.wikipedia.org/wiki/Signed_number_representations#Signed_magnitude_representation_(SMR). It's much easier to do maths on that, no special handling is required. The range is also improved because there's no wasted bit pattern for negative 0. To multiply, just do as normal fixed-point multiplication. The normal Q2.14 format will store value x/214 for the bit pattern of x, therefore if we have A and B then
So you just need to multiply A and B directly then divide the product by 214 to get the result back into the form x/214 like this
AxB = ((int32_t)A*B) >> 14;
需要舍入步骤才能获得最接近的值。您可以在中找到执行此操作的方法Q数字格式#数学运算 http://en.wikipedia.org/wiki/Q_%28number_format%29#Math_operations。舍入到最接近的最简单方法就是添加回最后移出的位(即第一个小数位),如下所示
AxB = (int32_t)A*B;
AxB = (AxB >> 14) + ((AxB >> 13) & 1);
您可能还想阅读这些
-
定点运算 http://en.wikipedia.org/wiki/Fixed-point_arithmetic.
- 模拟定点除法/乘法 https://stackoverflow.com/q/5028986/995714
- C# 中的定点数学? https://stackoverflow.com/q/605124/995714
用 2 位可以表示 [-2, 1] 的整数范围。因此,使用 Q2.14 格式,-0.25 将存储为11.11000000000000
。使用 1 个符号位只能表示 -1、0、1,并且这会使计算更加复杂,因为您需要拆分符号位,然后在最后将其组合回来。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)