如何在python中计算非常大的数字并将其写入文件?

问题描述 投票:1回答:1

这似乎是一个重复的问题,也许是,但是我检查了许多其他来源,但所有解决方案似乎都不起作用。我要计算的数字是999,999 ^ 999,999,这个数字毫无意义,但是我已经尝试了一段时间了。我想将结果写入文本文件。我通常会收到Overflow错误,在尝试了另一个问题的解决方案之后,我开始收到不同的Overflow消息。有什么办法可以计算这个数字?如果python无法做到,还可以吗?

此时我的代码:

from decimal import Decimal

#Attempt 2 (Attempt 1 was just print(999999**999999))
a = Decimal(999999**999)
a = a**(2) #Not close enough. 2.0002895717 would be perfect, but that would cause another Overflow: "OverflowError: int too large to convert to float"
print(a)
open("number.txt","x").write(str(a))

#Attempt 3, I tried breaking down the power into it's square root, and then that into it's square roots
massiveNumber = Decimal(999999**31.6227608)
massiveNumber = Decimal(massiveNumber**Decimal(31.6227608))
massiveNumber = Decimal(massiveNumber**Decimal(31.6227608))
massiveNumber = Decimal(massiveNumber**Decimal(31.6227608))

open("number.txt","w").write(str(massiveNumber))

错误:

Traceback (most recent call last):
  File "unknowablenumber.py", line 13, in <module>
    massiveNumber = Decimal(massiveNumber**Decimal(31.6227608))
decimal.Overflow: [<class 'decimal.Overflow'>]
python python-3.x digits exponent overflowexception
1个回答
2
投票

是,decimal可以准确,快速地完成它,但是您需要提高其使用的内部精度:

import decimal
with decimal.localcontext() as ctx:
    ctx.prec = decimal.MAX_PREC
    ctx.Emax = decimal.MAX_EMAX
    ctx.Emin = decimal.MIN_EMIN

    n = decimal.Decimal(999999)
    huge = n ** n
    s = str(huge)
    print(len(s))
    print (s[:10], "...", s[-10:])

显示:

5999994
3678796251 ... 9998999999

作为健全性检查,

>>> import math
>>> math.log10(999999) * 999999
5999993.565705735
>>> 10 ** .565705735
3.67879624904532
>>> pow(999999, 999999, 10**10)
9998999999

所以decimal的结果具有正确的数字位数,前导数字匹配,而最后10位完全正确。

© www.soinside.com 2019 - 2024. All rights reserved.