What is the largest number a decimal class can handle?

My program calculates the mathematical constant e, which is irrational. To do this, I needed to get factorials of very large numbers.

int cannot handle numbers greater than 170 !. (I found that the largest Google calculator can handle 170.654259, but I'm not sure how a non-integer can be factorized.) float cannot handle very large numbers either.

I calculated e to 750,000 digits, and math.factorial(750000) is a staggering, large amount. However, Decimal dealt with this with obvious ease.

How large can a Decimal handle before an OverflowError is raised? Is the size different in Python 2 and Python 3?

+6
source share
2 answers

What is the largest number a decimal class can handle?

The largest value is infinity:

 >>> from decimal import Decimal >>> Decimal('Inf') Decimal('Infinity') 

The largest representable final number on this platform depends on decimal.MAX_EMAX :

 >>> from decimal import Context, MAX_EMAX >>> d = Context(Emax=MAX_EMAX, prec=1).create_decimal('9e'+str(MAX_EMAX)) >>> d.is_finite() True >>> d.next_plus() Decimal('Infinity') >>> d Decimal('9E+999999999999999999') 

The number of significant digits depends on decimal.MAX_PREC , for example, to calculate e with a given accuracy:

 >>> from decimal import Context >>> Context(prec=60).exp(1) Decimal('2.71828182845904523536028747135266249775724709369995957496697') 

The constants ( MAX_EMAX , MAX_PREC ) are only applicable for the implementation of C. The Pure Python version can use larger values:

 >>> from decimal import Context, MAX_EMAX >>> Context(Emax=MAX_EMAX+1, prec=1).create_decimal('9e'+str(MAX_EMAX+1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: valid range for Emax is [0, MAX_EMAX] >>> from _pydecimal import Context, MAX_EMAX >>> Context(Emax=MAX_EMAX+1, prec=1).create_decimal('9e'+str(MAX_EMAX+1)) Decimal('9E+1000000000000000000') 
+6
source

It depends on the context that you provide for the Decimal object. From the documentation documentation :

class decimal.Context (prec = None, rounding = None, traps = None, flags = None, Emin = None, Emax = None, capitals = 1)

Emax and Emin control the boundaries of your decimal. If the indicator is greater than Emax or less than Emin , there will be an overflow signal. You can look at the fields in decimal.defaultContext to find out what they are by default, or decimal.getContext() to find out what they represent at any given time.

Edit: As @davidism pointed out, you are not getting accurate answers from decimal calculations. By default, the accuracy of the module is 28. Thus, all integers up to 9999999999999999999999999999999 (28 nines) can be represented exactly, and higher numbers can be rounded.

+1
source

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


All Articles