Help us understand the problem. What is going on with this article?

コンピューターでの微分

More than 1 year has passed since last update.

参考:ゼロから作る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
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away