How can a calculation temporarily change decimal precision?

localcontext provides a temporary decimal context and restores the enclosing settings on exit.

Python example and interpretation

One seventh gives 0.143 at three significant digits. Leaving the context does not restore lost digits in a value already rounded.

from decimal import Decimal,localcontext,getcontext
before=getcontext().prec
with localcontext() as ctx:
    ctx.prec=3
    value=Decimal(1)/Decimal(7)
[str(value),getcontext().prec==before]

Result ['0.143', True]

中文

如何临时改变精度且不影响后续计算?

localcontext 在局部作用域中复制十进制上下文,可在退出后恢复外部设置。

Python 算例与适用条件

三位有效数字下计算七分之一,得到 0.143。这个已舍入的结果不会在退出作用域后自动补回精度。

from decimal import Decimal,localcontext,getcontext
before=getcontext().prec
with localcontext() as ctx:
    ctx.prec=3
    value=Decimal(1)/Decimal(7)
[str(value),getcontext().prec==before]

结果 ['0.143', True]

References / 参考来源

Keep reading / 继续阅读