[英]How to calculate and write a very, very large number to a file in python?
This may seem like a duplicate question, and maybe it is, but I've checked many other sources and none of the solutions seem to work.这似乎是一个重复的问题,也许确实如此,但我检查了许多其他来源,但似乎没有一个解决方案有效。 The number I'm trying to calculate is 999,999^999,999, and it's pointlessly large, but I've been trying to get it for a while now.
我要计算的数字是 999,999^999,999,而且它毫无意义地大,但我已经尝试了一段时间了。 I want to write the result to a text file.
我想将结果写入文本文件。 I usually get Overflow errors, and after trying a solution for another question, I started getting different Overflow messages.
我通常会遇到溢出错误,在尝试解决另一个问题后,我开始收到不同的溢出消息。 Is there any way I can calculate this number?
有什么办法可以计算出这个数字吗? If python can't do it, can something else?
如果 python 做不到,还能做点别的吗?
My code at this point:我此时的代码:
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))
The error:错误:
Traceback (most recent call last):
File "unknowablenumber.py", line 13, in <module>
massiveNumber = Decimal(massiveNumber**Decimal(31.6227608))
decimal.Overflow: [<class 'decimal.Overflow'>]
Yes, decimal
can do it exactly, and quickly, but you need to boost the internal precision it uses:是的,
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:])
That displays:这显示:
5999994
3678796251 ... 9998999999
As a sanity check,作为健全性检查,
>>> import math
>>> math.log10(999999) * 999999
5999993.565705735
>>> 10 ** .565705735
3.67879624904532
>>> pow(999999, 999999, 10**10)
9998999999
so the result from decimal
has the right number of digits, the leading digits match, and the last 10 digits are exactly right.所以
decimal
的结果有正确的位数,前导数字匹配,最后 10 位数字完全正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.