Python decimal precision

For some reason, a decimal object loses precision when multiplied. Therefore, there is no reason. Please check the test and enlighten me.

from decimal import * getcontext().prec = 11 a = Decimal('5085.28725881485') b = 1 print getcontext() print 'a = '+str(a) print 'b = '+str(b) print 'a * b = '+str(a * b) 

And the conclusion:

 Context(prec=11, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[DivisionByZero, InvalidOperation, Overflow]) a = 5085.28725881485 b = 1 a * b = 5085.2872588 

Not sure if this is relevant, but python2.6 is used.

+6
source share
1 answer

The accuracy that you specify in the context (11 places) applies only when performing calculations, and not when creating decimal.Decimal objects - and the result, 5085.2872588 really obeys this limit. Using 1 , since the multiplier does not change the rules regarding accuracy; the result of arithmetic operations always takes into account the accuracy.

If you were looking for decimal.Decimal to return a number rounded to a certain number of places, the create_decimal method of the create_decimal object will do this for you.

+11
source

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


All Articles