2

Rounding obscenely large numbers with a lot of decimals gives an error. What's the limit on this type of decimal rounding? I'm very much a beginner with Python so I'm not sure if there's another way around this.

from decimal import *
print(round(Decimal((0.123456789123456789123456789123456789123)+12345678912345678912345678), 2))

Output:

12345678912345678704279552.00

Notice the extra digit on the int:

from decimal import *
print(round(Decimal((0.123456789123456789123456789123456789123)+123456789123456789123456789), 2))

Output:

Traceback (most recent call last):
File "", line 1, in
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

nmpereira
  • 43
  • 3

1 Answers1

5

Contrary to common misconception, the decimal module does not perform exact arithmetic. It performs adjustable-precision, decimal, floating-point arithmetic.

The decimal module defaults to 28-decimal-digit precision. The rounding operation you requested needs at least 29-digit precision, and rather than silently giving you less precision, decimal throws an error for this particular operation.

Of course, the operations you wanted to perform involve much higher than 29-digit precision, but because you did half your math in float arithmetic instead of decimal arithmetic, you lost most of your precision before decimal could even get involved. float has a little less than 16 decimal digits of precision. Wrapping a float computation in a Decimal call won't do the math in Decimal arithmetic; you need to start with Decimal:

import decimal
decimal.getcontext().prec = 100 # enough
print(round(decimal.Decimal('0.123456789123456789123456789123456789123')+
            decimal.Decimal('123456789123456789123456789'), 2))
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thank you, this solves my problem. I actually found another thread that addresses something similar. Will leave it here for future seekers. It gives some additional information. https://stackoverflow.com/questions/42868278/decimal-invalidoperation-divisionimpossible-for-very-large-numbers – nmpereira Apr 07 '21 at 06:43