[PYTHON] Avoid the warning [invalid value encountered in true_divide] when dividing by zero

Introduction

This is a Python learning memo.

problem

If there are 0s in the array created by numpy, dividing by 0 will give a warning. (Of course)

problem.py


import numpy as np

A = np.array([0, 1, 2])
B = np.array([0, 1, 1])

print(A/B)
output> RuntimeWarning: invalid value encountered in true_divide
  print(A/B)
[nan  1.  2.]

A warning is issued, and the part divided by zero is nan.

Solution

solved.py


import numpy as np

A = np.array([0, 1, 2], dtype=float)
B = np.array([0, 1, 1], dtype=float)

C = np.divide(A, B, out=np.zeros_like(A), where=B!=0)
print(C)
output> [0.  1.  2.]

np.zeros_like (A) returns a zero-filled array of the same shape as A. You can also use np.divide (A, B) to divide A by B. According to the documentation, out is the place to save the results and where is the option to specify conditions for all inputs. 0 is assigned to the calculation result of the place where where is false (B [0] in this case).

in conclusion

Sure, the warning is gone, but it can help, so I'm wondering if it's really a good solution.

Thank you for visiting. If you have any suggestions, please leave them in the comments section.

Reference URL

https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero (viewed February 24, 2020) https://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html(2020年2月24日閲覧) https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros_like.html(2020年2月24日閲覧)

Recommended Posts

Avoid the warning [invalid value encountered in true_divide] when dividing by zero
[Numpy] Avoid division by zero warning
Search by the value of the instance in the list
Multiply the x-axis value by n when plotting with pylab
Notes on coloring by value in the matplotlib scatter plot
Be careful when specifying the default argument value in Python3 series
What to do when the value type is ambiguous in Python?