python十进制量化vs prec在上下文中

Jam*_*Lin 5 python decimal

考虑以下十进制舍入方法:

使用量化:

>>> (Decimal('1')/Decimal('3')).quantize(Decimal('0.00'), rounding=ROUND_HALF_UP)
Decimal('0.33')
Run Code Online (Sandbox Code Playgroud)

使用上下文:

>>> ctx = Context(prec=2, rounding=ROUND_HALF_UP)
>>> setcontext(ctx)
>>> Decimal('1')/Decimal('3')
Decimal('0.33')
Run Code Online (Sandbox Code Playgroud)

四种舍入方法之间是否存在实际差异?任何陷阱?是否使用上下文更优雅,以便我可以使用with语句为整个计算块?

Jam*_*Lin 2

>>> from decimal import Decimal, ROUND_HALF_UP, setcontext, Context
>>> ctx = Context(prec=2, rounding=ROUND_HALF_UP)
>>> setcontext(ctx)
>>> total = Decimal('0.002') + Decimal('0.002')
>>> total
Decimal('0.004')
Run Code Online (Sandbox Code Playgroud)

它实际上不会像我预期的那样自动舍入,因此我无法将其用于整个计算块。

另一个问题是,临时值被四舍五入,这会损失精度。

from decimal import Decimal, ROUND_HALF_UP, getcontext, setcontext, Context

class FinanceContext:
    def __enter__(self):
        self.old_ctx = getcontext()
        ctx = Context(prec=2, rounding=ROUND_HALF_UP)
        setcontext(ctx)
        return ctx

    def __exit__(self, type, value, traceback):
        setcontext(self.old_ctx)


class Cart(object):
    @property
    def calculation(self):
        with FinanceContext():
            interim_value = Decimal('1') / Decimal('3')
            print interim_value, "prints 0.33, lost precision due to new context"

            # complex calculation using interim_value
            final_result = ...
            return final_result
Run Code Online (Sandbox Code Playgroud)