Python:溢出错误:数学范围错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4050907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:02:26  来源:igfitidea点击:

Python: OverflowError: math range error

pythonmathoverflow

提问by Harpal

I get a Overflow error when i try this calculation, but i cant figure out why.

尝试此计算时出现溢出错误,但我不知道为什么。

1-math.exp(-4*1000000*-0.0641515994108)

采纳答案by Glenn Maynard

The number you're asking math.exp to calculate has, in decimal, over 110,000 digits. That's slightly outside of the range of a double, so it causes an overflow.

您要求 math.exp 计算的数字以十进制表示,超过 110,000 位。这稍微超出了 double 的范围,因此会导致溢出。

回答by Alin Purcaru

This may give you a clue why:

这可能会给你一个线索:

http://www.wolframalpha.com/input/?i=math.exp%28-4*1000000*-0.0641515994108%29

Notice the 111442 exponent.

注意 111442 指数。

回答by MAK

I think the value gets too large to fit into a doublein python which is why you get the OverflowError. The largest value I can compute the expof on my machine in Python is just sligthly larger than 709.78271.

我认为该值太大而无法放入doublepython 中,这就是为什么你得到OverflowError. 我可以exp在我的机器上用 Python计算的最大值略大于 709.78271。

回答by Vatsal

To fix it use:

要修复它,请使用:

try:
    ans = math.exp(200000)
except OverflowError:
    ans = float('inf')

回答by mpetric

Try np.exp() instead of math.exp()

尝试 np.exp() 而不是 math.exp()

Numpy handles overflows more gracefully, np.exp(999) results in inf and 1. / (1. + np.exp(999)) therefore simply results in zero

Numpy 更优雅地处理溢出, np.exp(999) 导致 inf 和 1. / (1. + np.exp(999)) 因此只会导致零

import math 
import numpy as np

print(1-np.exp(-4*1000000*-0.0641515994108))

回答by anonymous

Unfortunately, no one explained what the real solution was. I solved the problem using:

不幸的是,没有人解释真正的解决方案是什么。我使用以下方法解决了问题:

from mpmath import *

从 mpmath 导入 *

You can find the documentation below:

您可以在下面找到文档:

http://mpmath.org/

http://mpmath.org/