Decimal .quantize raises InvalidOperation

looking at Decimal

, i tried to convert pi

to various parameters. I can call pi.quantize()

with the first two options below, but with the third version it comes up InvalidOperation

. the accuracy pi

doesn't come close to this ...

from decimal import Decimal

pi  = Decimal('3.1415926535897932384626433832795028841971693993751058209749445'
              '923078164062862089986280348253421170679')
print(pi) # prints same as the string above

# just print formatted
print('{:1.7f}'.format(pi))

print(pi.quantize(Decimal('1.0')))     # 3.1
print(pi.quantize(Decimal('1.00')))    # 3.14
print(pi.quantize(Decimal('1.000')))   # raises InvalidOperation

      

what's going on here? I didn't understand what this function should do? why does this exception happen in 1.000

and not before / after?

the same exception happens with '0.001'

as an argument for quantize

.

+3


source to share


1 answer


Per documentation :

... if the length of the coefficient after the quantization operation is equal to the precision, then it is signaled InvalidOperation

.

Therefore, your precision should be set to 3

; to test it try:



from decimal import Decimal, getcontext

print(getcontext().prec)

      

You should read the documentation on contexts to understand what they are for and how to use them. For example, you can try:

from decimal import Context, Decimal, getcontext

...

print(pi.quantize(Decimal('1.000'), Context(prec=4))) 

      

+7


source







All Articles