MATLAB不动点函数“fi”在Python中的等价性

2024-09-26 22:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

MATLAB有一个函数“fi”来表示不动点格式中的分数。它的语法是

fi(fraction, sign, word_length, fraction_length).

例如,要用8位字长度和7位小数长度表示定点中的-0.4,它将返回以下值:

^{pr2}$

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


Tags: 函数格式语法length分数fi定点word
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:55

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

Example

>>> 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

相关问题 更多 >

    热门问题