[英]"RuntimeWarning: overflow encountered in exp", but not when using an array
I am implementing the following formula:我正在实施以下公式:
in Python (with SciPy and NumPy).在 Python 中(使用 SciPy 和 NumPy)。 I wrote the following expression:我写了以下表达式:
def fokker_plank_solution_1_sur(t, k, c, x_0):
if k == 0 & c == 0:
pass
else:
print("Case 2")
t_1 = (k - c)/(k - 2*c)
t_2 = np.exp((k * x_0 + k*(k - 2*c)*t))
t_3 = erfc((x_0 + 2 * (k - c) * t)/(np.sqrt(4*t)))
t_4 = 0.5
t_5 = erfc((- x_0 + 2 * c * t)/np.sqrt(4 * t))
t_6 = k/(k - (2 * c))
t_7 = np.exp(2 * c * x_0)
t_8 = erfc((x_0 + 2*c*t)/(np.sqrt(4*t)))
y = t_1 * t_2 * t_3 + t_4 * (t_5 - t_6 * t_7 * t_8)
return y
Case 1: If I am using the following conditions, I am getting "good" numbers (t_2 = 1.94e+05) and the plot案例 1:如果我使用以下条件,我会得到“好”数字 (t_2 = 1.94e+05) 和情节
D = .25
x_val = np.linspace(1,500,250)
c = 0
x_0 = 5
for k in [.8]:
y_val = fokker_plank_solution_1_sur(x_val * D, k, c, x_0)
# print(np.concatenate((x_val.reshape([250,1]), y_val.reshape([250,1])), axis = 1))
plt.plot(x_val, y_val)
Case 2: However, if I am just putting this in the console,情况 2:但是,如果我只是将它放在控制台中,
fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8)
I get the return我得到回报
t_2 = np.exp((k * x_0 + k*(k - 2*c)*t))
RuntimeWarning: overflow encountered in exp
After some search, I found t_2 is just getting too big, to be further processed ( 1 , 2 ), t_2 is then经过一番搜索,我发现 t_2 太大了,需要进一步处理 ( 1 , 2 ),然后 t_2
e^1258.0
-> So the question now is, why can python calculate numbers, when using a NumPy array indirectly (case 1), but not when using the NumPy array directly (case 2)? -> 所以现在的问题是,为什么 python 可以在间接使用 NumPy 数组(情况 1)时计算数字,而在直接使用 NumPy 数组(情况 2)时不能计算数字? Thank you for reading this far.感谢您阅读到这里。
It depends on how you tell NumPy to handle errors.这取决于您如何告诉 NumPy 处理错误。 You can control it with seterr or errstate .您可以使用seterr或errstate来控制它。
For example:例如:
>>> with np.errstate(all='ignore'):
... print(fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8))
nan
>>> with np.errstate(all='warn'):
... print(fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8))
RuntimeWarning: overflow encountered in exp
t_2 = np.exp((k * x_0 + k * (k - 2 * c) * t))
RuntimeWarning: invalid value encountered in double_scalars
y = t_1 * t_2 * t_3 + t_4 * (t_5 - t_6 * t_7 * t_8)
nan
>>> with np.errstate(all='raise'):
... print(fokker_plank_solution_1_sur(np.array((50.0)) * .25, 10, 0, 0.8))
Error
Traceback (most recent call last):
[...]
t_2 = np.exp((k * x_0 + k * (k - 2 * c) * t))
FloatingPointError: overflow encountered in exp
You are likely using a different setting in your program and when you call the function from the console.您可能在程序中以及从控制台调用该函数时使用了不同的设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.