我正在编写一个用算术编码进行编码的小代码.我需要设定一个确定的精度,但我必须做错事.这是代码:
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)
Run Code Online (Sandbox Code Playgroud)
正如我在python文档中读到的getcontext().prec应该设置我愿意使用的精度.在一些迭代之后,d_start和d_with非常小(~e ^ -20)并且变量start和width从那一刻起保持相同的valor.
如果需要进一步的信息,请不要犹豫要求.
提前致谢
编辑1:正确缩进代码
编辑2:我在每个总和之后打了一个d_start的打印来表示我的意思是说"并且变量的开始和宽度从那一刻起保持相同的价值."
在这里你有结果:
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
Run Code Online (Sandbox Code Playgroud)
问题是getcontext().prec它只用于decimal.Decimal变量......你定义start和width浮动.
你应该强制使用Decimal,例如那样(假设a 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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
735 次 |
| 最近记录: |