9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ゼロで割ったときの警告【invalid value encountered in true_divide】を回避する

Posted at

はじめに

 Pythonの学習メモです。

問題

 numpyで作成した配列に0があった場合、0で割ると警告が出ます。(当たり前)

problem.py
import numpy as np

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

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

 警告が出て、ゼロで割った箇所がnanになっています。

解決方法

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)
出力> [0.  1.  2.]

 np.zeros_like(A)は、Aと同じ形のゼロで埋められた配列を返します。また、np.divide(A,B)でAをBで割る演算を行えます。ドキュメントによると、outは結果を保存する場所、whereは全入力に対して条件を指定するオプションです。whereが偽となる箇所(この場合はB[0])の計算結果には0が代入されます。

おわりに

 確かに警告はなくなりましたが、それに助けられることもあるので、本当に解決して良かったのかは疑問です。

 ご覧いただきありがとうございました。ご指摘等ございましたらコメント欄にお願いします。

参考URL

https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero (2020年2月24日閲覧)
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日閲覧)

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?