Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Decimal with a large exponent in Python 3?

Tags:

Python 3 seems to have some arbitrary limit to Decimal sizes that Python 2 does not. The following code works on Python 2:

Decimal('1e+100000000000000000000')

But on Python 3 I get:

decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Increasing the precision does not help. Why is this happening? Is there something I can do about it?

like image 242
Alex Grönholm Avatar asked Jun 08 '16 12:06

Alex Grönholm


1 Answers

It would appear that Decimals actually can't hold arbitrarily long numbers:

>>> d = Decimal('10') ** Decimal('100000000000000000000')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.Overflow: [<class 'decimal.Overflow'>]

Indeed, I never heard that arbitrarily long numbers was the point of Decimal - just proper rounding and decimals of arbitrary precision. If you want an arbitrarily long number, that's what longs are for, and in Python3 that's just what you've got.

>>> d = 10 ** 100000000000000000000

(Though it takes a long long while to compute this. My Mac book with I believe a core i5 still hasn't finished after a couple of minutes. Heck, even the string 1, followed by all those zeroes, is going to be really really big.)

For further kicks and grins, I discovered that you can configure the overflow value, apparently, though you still can't get such a whopping big number:

>>> from decimal import getcontext
>>> getcontext().Emax = 100000000000000000000
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C ssize_t
like image 121
Wayne Werner Avatar answered Sep 28 '22 04:09

Wayne Werner