3
2

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 3 years have passed since last update.

np.logとかで-infにしないようにしたい

Posted at

TL;DR

np.clipで最小値(最大値)を指定する!

実行環境

  • python: 3.7.7
  • numpy: 1.19.1

なにがおきるの?

pythonのfloat型ではおおよそ1e-323未満の値は0.0になってしまいます.
pythonのfloat型は多くの環境では,-1.7976931348623157e+308から1.7976931348623157e+308の間で範囲を取りうる.

$ python
>>> a = 1e-323
>>> b = 1e-324
>>> print(a)
 1e-323
>>> print(b)
 0.0

bが0.0になってしまうため,このbに対してlogをとってしまうとエラーがでて-infになってしまいます.
また,0割の警告も出てきます.

>>> import numpy as np
>>> b = 1e-324
>>> np.log(b)
 __main__:1: RuntimeWarning: divide by zero encountered in log
 -inf

解決策

np.clipで最小値(最大値)を指定してあげる.

>>> import numpy as np
>>> b = 1e-324
>>> np.log(np.clip(a=b, a_min=1e-323, a_max=1e+10))
 -743.7469247408213

最小値(最大値)を指定してあげることで,floatの範囲外の値が入った時でも一応計算できるようになります.ただ,最小値(最大値)を超えた値はそれぞれ設定した値に丸め込まれてしまうのでその分誤差が大きくなってしまうデメリットもあります.

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?