首页 > 解决方案 > Python中等效的MATLAB定点函数“fi”

问题描述

MATLAB 有一个函数“ fi ”用于表示定点方案中的分数。它的语法是

fi(fraction, sign, word_length, fraction_length).

例如,要使用 8 位 word_length 和 7 位 fraction_length 以定点表示 -0.4,它返回以下内容:

fixed_number = fi(-0.4, 1, 8, 7) = -0.3984
fixed_number.int = -51
fixed_number.bin = 11001101

查询:我们可以在 Python 中做类似的事情吗?有什么功能可以执行此操作吗?

标签: pythonmatlab

解决方案


Python 的 rig 库可用于此目的。它支持浮点到固定和固定到浮点的转换。

示例

>>> from rig.type_casts import float_to_fp, fp_to_float

>>> # Create a function to convert a float to a signed fractional
>>> # representation with 8 bits overall and 4 fractional bits (S3.4)
>>> s34 = float_to_fp(signed=True, n_bits=8, n_frac=4)
>>> hex(int(s34(0.5)))
'0x8'
>>> hex(int(s34(-7.5)))
'-0x78'

>>> # ...and make a function to convert back again!
>>> f4 = fp_to_float(n_frac=4)
>>> f4(0x08)
0.5
>>> f4(-0x78)
-7.5

推荐阅读