与Python中的MATLAB定点函数“ fi”等效

时间:2018-08-30 12:02:49

标签: python python-3.x python-2.7 matlab

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

fi(fraction, sign, word_length, fraction_length).

例如,要以8位word_length和7位分数_length表示定点中的-0.4,它将返回以下内容:

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我推荐 fxpmath 模块,它与fi函数非常相似。

Git回购网址:https://github.com/francof2a/fxpmath

from fxpmath import Fxp

x = Fxp(-0.4, True, 8, 7)   # (val, signed, n_word, n_frac)

print(x())                  # original format = float
print(x.val)                # (raw) int value
print(x.bin())              # binary representation

结果:

-0.3984375
-51
11001101