runtimewarning: invalid value encountered in true_divide

How this runtimewarning: invalid value encountered in true_divide occur?

Cause of this runtimewarning: invalid value encountered in true_divide is by attempting to divide a number by zero. When this occurs, the error message “Invalid value encountered in true_divide” will be displayed.

 

To fix this error, you will need to determine what caused the division by zero error. Once you have determined the cause, you can then take steps to fix it. In some cases, you may need to enter a value that is not zero into the equation in order to continue the division.

 

If you are getting this error while trying to divide a number by another number, it is likely that you have entered the wrong numbers into the equation. Make sure that you have entered the correct numbers into the equation, and that the division is being performed between the correct numbers.

 

If you are getting this error while trying to divide a number by a variable, it is likely that you have not defined the variable correctly.

 

For Eg.

import numpy as np
  
# Create two Numpy arrays
arr1 = np.array([2, 9, 0])
arr2 = np.array([1, 5, 0])
  
# divide the values of arr1 by the values of arr2
np.divide(arr1, arr2)

Output:

runtimewarning: invalid value encountered in true_divide

 

Explanation :

In the above program, we are trying to divide the values of arr1 with arr2 values. And hence it returns the quotient value.

    • 2/1=2   this is a valid operation
    • 9/5=1.8 this is a valid operation
    • 0/0    this is an invalid operation so we see a Warning and return the result as the runtimewarning: invalid value encountered in true_divide

We can eliminate this runtime warning by using this syntax.

Syntax: numpy.seterr(invalid=’ignore’)

 

We can use this in our program like this

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

# Create two Numpy arrays
arr1 = np.array([2, 9, 0])
arr2 = np.array([1, 5, 0])

# divide the values of arr1 by the values of arr2
np.divide(arr1, arr2)

Output:

 

 

Also, read our python tutorials.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *