RuntimeWarning: Invalid value encountered in true_divide in Python

Dung Do Tien May 07 2022 503

I'm a student and programming with Python is a subject in my class. It's difficult for me to start learning it. I have two arrays that need division together, division item by item. I'm using numpy divide() method, like this:

import numpy as np

dividend = np.array([10, 0, 187, 58, 88, 168, 275, 77, 88, 0])
divisor = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])

print(np.divide(dividend, divisor))

When I was running the code above it's not throw any exceptions but had a warning show RuntimeWarning: Invalid value encountered in true_divide

[10.  0. 62.33333333 14.5  17.6  28.  39.28571429  9.625  9.77777778   nan]

main.py:6: RuntimeWarning: invalid value encountered in true_divide
  print(np.divide(dividend, divisor))

It's difficult to understand, anyone can explain it to help me?

Thanks in advance.

Have 1 answer(s) found.
  • M

    Mary Christ May 07 2022

    The NumPy divide() method will return the quotient value after the division. Hence in our case following division takes place.

    1. 10/1 = 10 (good, valid format)
    2. 0/2 = 0 (good, valid format)
    3. 187/3 = 62.3 (good, valid format)
    4. 58/4 = 14.5 (good, valid format)
    5. 88/5 = 17.6 (good, valid format)
    6. 168/6 = 28 (good, valid format)
    7. 275/7 = 39.2 (good, valid format)
    8. 77/8 = 9.6 (good, valid format)
    9. 88/9 = 9.7 (good, valid format)
    10. 0/0 = infinity  (This would be treated as an invalid operation as 0 divisible by 0 would lead to nan; hence we get the warning)

     So how to fix RuntimeWarning: invalid value encountered in true_divide?

    Solution 1: Ignore the invalid warning message by using seterr() method of numpy

    import numpy as np
    
    dividend = np.array([10, 0, 187, 58, 88, 168, 275, 77, 88, 0])
    divisor = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
    
    np.seterr(invalid='ignore') # Add more this line
    
    print(np.divide(dividend, divisor))

    Solution 2 : remove any item 0/0 in two array.

    I hope this explanation will helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close