Open In App

How to Fix: Invalid value encountered in true_divide

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Python3




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


Output:

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

Explanation:

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

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.

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

Python3




# import necessary packages
import numpy as np
 
# Create 2 Numpy arrays
Array1 = np.array([6, 2, 0])
Array2 = np.array([3, 2, 0])
 
# Suppress/hide the warning
np.seterr(invalid='ignore')
 
# divide the values in Array1 by the
# values in Array2
np.divide(Array1, Array2)


Output:

array([ 2.,  1., nan])


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads