Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeWarning: invalid value encountered in divide

People also ask

How to ignore invalid value encountered in true_ divide?

Solution: We can fix this Runtime Warning by using seterr method which takes invalid as a parameter and assign ignore as a value to it. By that, it can hide the warning message which contains invalid in that.

What is True_divide?

In Python, the true_divide() function is used to return the element-wise true division of inputs x1 and x2 .


I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

  • http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.


To prevent division by zero you could pre-initialize the output 'out' where the div0 error happens, eg np.where does not cut it since the complete line is evaluated regardless of condition.

example with pre-initialization:

a = np.arange(10).reshape(2,5)
a[1,3] = 0
print(a)    #[[0 1 2 3 4], [5 6 7 0 9]]
a[0]/a[1]   # errors at 3/0
out = np.ones( (5) )  #preinit
np.divide(a[0],a[1], out=out, where=a[1]!=0) #only divide nonzeros else 1

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!