我必须计算2达到8635的幂。当我计算2 ^ 8635时遇到了这个错误。任何建议如何在python中解决这个问题。使用十进制模块也无济于事。

math.exp(2**8635)
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    long(math.exp(2**8635))
OverflowError: long int too large to convert to float

最佳答案

您可以使用mpmath任意精度数学模块来计算exp(2**8635):

>>> from mpmath import mp
>>> mp.exp(2**mp.mpf(8635))

即使使用科学计数法,结果也相当大,因此我对它进行了一些字符串处理,方法是将指数复制并粘贴到字符串s中,然后用以下命令重新格式化:
>>> ' '.join([''.join(b) for b in zip(*[iter(s)]*10)])

使用mp.dps=20的精度的结果是

关于python - Python : overflow error long int too large to convert to float,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29865919/

10-10 16:42