How to Fix: Invalid value encountered in true_divide
In this article, we are going to fix, invalid values encountered in true_divide in Python. Invalid value encountered in true_divide is a Runtime Warning occurs when we perform an invalid division operation between elements of NumPy arrays. One of the examples of Invalid division is 0/0.
Note: As it is just a Warning the code won’t stop from its execution and return a Not a Number value i.e. nan (or) inf (infinity).
The division operation between NumPy arrays can be done using divide() which is present in NumPy package allows division operation between corresponding elements of 2 arrays.
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:9: RuntimeWarning: invalid value encountered in true_divide
if __name__ == ‘__main__’:
Result-array([ 2., 1., nan])
Here we are dividing the elements of Array1 by the elements of Array2. So 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 thrown and returns the result as Not a Number (nan).
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.
array([ 2., 1., nan])