Python vs prec decimal quantization in context

Consider the following decimal rounding approaches:

using quantization:

>>> (Decimal('1')/Decimal('3')).quantize(Decimal('0.00'), rounding=ROUND_HALF_UP) Decimal('0.33') 

using context:

 >>> ctx = Context(prec=2, rounding=ROUND_HALF_UP) >>> setcontext(ctx) >>> Decimal('1')/Decimal('3') Decimal('0.33') 

Are there any actual differences between the two rounding methods? Any bugs? Is using context more elegant so that I can use the with statement for the whole block of calculations?

+5
source share
1 answer
 >>> 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') 

It actually does not round automatically, as I expected, so I can not use it for the entire block of calculations.

Another problem: intermediate values ​​are rounded, which loses accuracy.

 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 
0
source

Source: https://habr.com/ru/post/1210372/


All Articles