我正在编写一个用于使用算术编码进行编码的小代码。我需要设置一个确定的精度,但我一定做错了什么。这是代码:
def encode(string, probabilities):
getcontext().prec = 28
start = 0.0
width = 1.0
for ch in string:
d_start, d_width = probabilities[ch]
start += d_start*width
width *= d_width
return random.uniform(start, start + width)
正如我在 python 文档中读到的那样,getcontext().prec 应该设置我愿意使用的精度。经过一些迭代后,d_start 和 d_with 非常小 (~ e^-20),并且从那一刻起变量 start 和 width 保持相同的值。
如果需要更多信息,请毫不犹豫地询问。
提前致谢
编辑 1:代码的正确缩进
编辑 2:我在每次求和后打印了 d_start 以显示我所说的“并且从那一刻起,变量 start 和 width 保持相同的强度。”
结果如下:
0.0
0.16
0.224
0.224
0.22784
0.22784
0.2280448
0.22812672
0.22812672
0.2281316352
0.2281316352
0.228131897344
0.228132002202
0.228132002202
0.228132008493
0.228132008493
0.228132008829
0.228132008963
0.228132008963
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
0.228132008971
最佳答案
问题是 getcontext().prec
仅用于 decimal.Decimal
变量...并且您定义了 start
和 宽度
作为 float 。
你应该强制使用 Decimal,例如那样(假设 from decimal import *
)
def encode(string, probabilities):
getcontext().prec = 28
start = Decimal('0.0')
width = Decimal('1.0')
for ch in string:
d_start, d_width = probabilities[ch]
start += Decimal(d_start)*width
width *= Decimal(d_width)
return random.uniform(float(start), float(start + width))
关于Python设置小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36885866/