こちらのQAを参考にして書けそうです。
StackOverflow - How do I catch a numpy warning like it's an exception (not just for testing)?
Python
1import warnings
2import numpy as np
3
4with warnings.catch_warnings():
5 warnings.filterwarnings('error')
6
7 for i in range(-5, 5):
8 try:
9 print(i, np.array([100]) / i)
10 except RuntimeWarning as e:
11 # print(e)
12 break
実行結果 paiza.io
-5 [-20.]
-4 [-25.]
-3 [-33.33333333]
-2 [-50.]
-1 [-100.]
ただ実際のところ、除数が0であるか事前に判定するのが楽なようにも思います。
numpy.seterrというものもあり、次のように書けます。
Python
1old_setting = np.seterr(divide='raise')
...と思いきや、上手く働いてくれないのです。なんでだろう。
追記:
tachikomaさんのコメントを受けて、次のように書けば良いことに気付きました。
Python
1old_setting = np.seterr(divide='raise', invalid='raise')
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/08 07:01