LoginSignup
1
5

More than 5 years have passed since last update.

コンピューターでの微分

Last updated at Posted at 2017-06-07

参考:ゼロから作るDeep Learning(p98 4.3.1)

関数fのx点での微分がしたい時どうすればいいか?
数学の公式のように計算してみると以下のようになる。

>この計算ができたら理想
>だけど丸め誤差のせいでnp.fload32(10e-50)=0.0になってしまう。
def numerical_diff(f, x):
  h = 10e-50
  return ( f(x+h) - f(x) ) / h

なので、以下のようにする。

def numerical_diff(f, x):
  h = 1e-4 # 0.00001
  return ( f(x+h) - f(x) ) / h

しかし、これだとx点と(x+h/2)点の差が0.00001ある。
その間の点(x+0.000005)の微分になってしまう。xとx+hの差を極小にできていないのでその分ズレがある。
x点での微分とは言えない。
以下のようにすれば関数fのx点での微分になる。

def numerical_diff(f, x):
  h = 1e-4 # 0.00001
  return ( f(x+h) - f(x-h) ) / (2*h)

ちなみに、微小な値を与えた時の差分によって微分を求めることを、数値微分という。

おまけ:どれだけ差が出るの?

import numpy as np
import matplotlib.pylab as plt

def function(x):
  return 0.01*x**2 + 0.1*x

def nd1(f, x):
  h = 1e-4 # 0.00001
  return ( f(x+h) - f(x) ) / h

def nd2(f, x):
  h = 1e-4 # 0.00001
  return ( f(x+h) - f(x-h) ) / (2*h)

# 真微分では0.2,0.3になるので、それに近ければ近いほどいい。
# nd1の場合
print(nd1(function, 5))  # => 0.20000099999917254
print(nd1(function, 10)) # => 0.3000009999976072
# nd2の場合
print(nd2(function, 5))  # => 0.1999999999990898
print(nd2(function, 10)) # => 0.2999999999986347
1
5
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
1
5