RuntimeWarning: Invalid value encountered in true_divide in Python
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.
- M0
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.- 10/1 = 10 (good, valid format)
- 0/2 = 0 (good, valid format)
- 187/3 = 62.3 (good, valid format)
- 58/4 = 14.5 (good, valid format)
- 88/5 = 17.6 (good, valid format)
- 168/6 = 28 (good, valid format)
- 275/7 = 39.2 (good, valid format)
- 77/8 = 9.6 (good, valid format)
- 88/9 = 9.7 (good, valid format)
- 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 usingseterr()
method ofnumpy
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.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.