我想知道是否有任何模块可以将浮点数转换为定点数。这里提到的定点在基数2中,因此一些示例如下:
不动点表达式= 2 ^ 1 + 2 ^ 0 + a * 2 ^ -1 + b * 2 ^ -2 .....
我发现的是某些模块可以执行以下操作:
输入为0.68751(浮点数),并指定一些精度(如3)
并且输出为0.6875,原因是0.5 + 0.125 + 0.0625
我看过模块Decimal
,它具有quantize
方法几乎完成了我想要的,但是它是二进制的,而不是十进制的。
是的,有一个python模块,fxpmath。您可以在以下位置找到更多信息:
https://github.com/francof2a/fxpmath
这里举个例子:
from fxpmath import Fxp
x = Fxp(0.68751, True, 8, 3) # (val, signed, n_word, n_frac)
print(x)
print('precision = {}\n'.format(x.precision))
y = Fxp(0.68751, True, 8, 4) # (val, signed, n_word, n_frac)
print(y)
print('precision = {}\n'.format(y.precision))
print(x+y)
结果:
0.625
precision = 0.125
0.6875
precision = 0.0625
1.3125