问题描述
我不断收到有关除法的运行时警告。 在下面的代码中,我使用了来自这个论坛的 a question 的答案,甚至从 this 导入了警告错误。
def alpha_n(V):
with np.errstate(divide='ignore'):
alph = np.where(V!= -55,0.01*(V+55)/(1-np.exp(-0.1*(V+55))),0.1)
return alph
RuntimeWarning: true_divide 中遇到无效值
如何正确定义函数以避免警告?
解决方法
In [26]: def alpha_n(V):
...: with np.errstate(invalid='ignore'):
...: alph = np.where(V!= -55,0.01*(V+55)/(1-np.exp(-0.1*(V+55))),0
...: .1)
...: return alph
...:
In [27]: alpha_n(np.array([1,2,3,-55]))
Out[27]: array([0.56207849,0.5719136,0.58176131,0.1 ])
除以 0 与无效值不同:
In [28]: 1/(1-np.exp(-0.1*(np.array([-55])+55)))
<ipython-input-28-ed83c58d75bb>:1: RuntimeWarning: divide by zero encountered in true_divide
1/(1-np.exp(-0.1*(np.array([-55])+55)))
Out[28]: array([inf])
In [29]: 0/(1-np.exp(-0.1*(np.array([-55])+55)))
<ipython-input-29-0d642b423038>:1: RuntimeWarning: invalid value encountered in true_divide
0/(1-np.exp(-0.1*(np.array([-55])+55)))
Out[29]: array([nan])