Python设置小数精度

标签 python python-3.x

我正在编写一个用于使用算术编码进行编码的小代码。我需要设置一个确定的精度,但我一定做错了什么。这是代码:

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/

相关文章:

python - 从 python 字典创建 pandas 数据框

Python JSONPath 过滤器表达式错误,jsonpath-rw 1.4.0 的意外字符

python - 嵌套列表 python

python - 访问/使用元组列表中的元素 python 3.x

python - 使用内存数据中的 Pygobject 和 Python 3 显示图像

python - 调用 `logging`会干扰其他模块

python - 如何在 Python 的列表中扩展列表?

python - 使用 Pandas Dataframe 中的另一列数据拆分列数据

python - 退出在 python shell 中编写的正在运行的 while 循环

python 2.7 : knowing if it's a list of list of list OR a list of list