. Advertisement .
..3..
. Advertisement .
..4..
I’m building a new program, but when I run it, an error pops up. The error displayed is as follows:
RuntimeWarning: invalid value encountered in true_divide
I have tried several workarounds, but they still do not get the desired results. If you have come across this situation and have a solution for the “invalid value encountered in true_divide” problem, pls let me know. This is what I do:
# import necessary packages
import numpy as np
# Create 2 Numpy arrays
Array1 = np.array([6, 2, 0])
Array2 = np.array([3, 2, 0])
# divide the values in Array1 by the
# values in Array2
np.divide(Array1, Array2)
Thanks.
The cause: This error happens because you are dividing the elements of Array1 by the elements of Array2. And it returns the quotient value.
6/3=2 (Valid Operation)
2/2=1 (Valid Operation)
0/0 which is an invalid operation so a Warning is shown and the result is not a Number (nan).
Solution: Using seterr method which takes invalid as a parameter and assign ignore as a value to it. By this way, the warning message which contains invalid in can be hiden.
Syntax: numpy.seterr(invalid=’ignore’)
Output:
This is why you will get the runtime warning.
Is that the inner expression?
Gets evaluated first and is run on all
diff_images
andb_0
elements (even if you ignore elements that involve division by zero). The warning occurs before any code that ignores these elements. This is why it is a warning, not an error. There are legitimate cases such as this where division-by-zero doesn’t pose a problem since it is being dealt with in a later operation.