使用 decimal.get_context().prec 给出错误

using decimal.get_context().prec gives error

我想计算浮点值 1/919 的最多 120 位小数。

import decimal  
get_context().prec = 120
result = decimal.Decimal(1) / decimal.Decimal(919)
print(result)

但这给出了错误:

module 'decimal' has no attribute 'get_context'

我该怎么办?

运行 你的代码,它只是输出:

NameError: name 'get_context' is not defined

您的问题有两种解决方案:

使用全局上下文

你够接近了,是 getcontext 而不是 get_context

>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 120
>>> Decimal(1) / Decimal(919)
Decimal('0.00108813928182807399347116430903155603917301414581066376496191512513601741022850924918389553862894450489662676822633297062')

使用特定上下文

如果您想要单个操作的精度,或者在您的上下文中有更大的灵活性,您可以创建它们:

>>> from decimal import Context
>>> context = Context(prec=120)
>>> context.divide(1, 919)
Decimal('0.00108813928182807399347116430903155603917301414581066376496191512513601741022850924918389553862894450489662676822633297062')