Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - What is the largest number the Decimal class can handle?

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

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

I calculated e to 750000 digits, and math.factorial(750000) is a mind-boggling, large number. Yet, Decimal handled it with apparent ease.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is the largest number the Decimal class can handle?

The largest magnitude is infinity:

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

The largest representable finite number on a given 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 e.g., to calculate e with the given precision:

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

The constants (MAX_EMAX, MAX_PREC) are only relevant for the C implementation. 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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...