Tobiasz
Tobiasz

Reputation: 13

Python numpy Runtime warning using np.where np.errstate and warnings 'error'

I keep getting the runtime warning about division. In the code below, I used the answer of a question from this forum and even imported warnings error from 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: invalid value encountered in true_divide

How could I define the function properly to avoid warnings?

Upvotes: 1

Views: 684

Answers (1)

hpaulj
hpaulj

Reputation: 231335

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       ])

Divide by 0 is different from invalid value:

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])

Upvotes: 1

Related Questions