python - 如何计算一个非常非常大的数字并将其写入python中的文件?
问题描述
这似乎是一个重复的问题,也许确实如此,但我检查了许多其他来源,但似乎没有一个解决方案有效。我要计算的数字是 999,999^999,999,而且它毫无意义地大,但我已经尝试了一段时间了。我想将结果写入文本文件。我通常会收到溢出错误,在尝试解决另一个问题后,我开始收到不同的溢出消息。有什么办法可以计算出这个数字吗?如果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'>]
解决方案
是的,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
所以结果 fromdecimal
有正确的位数,前导数字匹配,最后 10 位数字完全正确。
推荐阅读
- mysql - MySQL 在 XAMPP 上意外关闭 - 在 IP 上创建服务器套接字:'::'
- java - 读取 Jena 模型时出现错误的 URI 异常
- ios - Flutter - 字体在不同版本的 iOS 上表现不同
- unity3d - Unity NavMesh 路径反向
- sql - 使用 sql/sequelize 通过 userId 获取喜欢的帖子并获取帖子的点赞数
- date - 如何在ggplots中将日期中断设置为每月的第一天
- javascript - 如何编写 JavaScript Array.from() 映射函数?
- javascript - 我的问题是我想在登录后在母版页布局中启用一个 html 元素,但我不能
- javascript - 获取输入值的 DOM xss 攻击
- html - 悬停图像或文本时如何更改图像和文本。仅使用 CSS