edo1z blog

プログラミングなどに関するブログです

Python - 数値微分

微分はある瞬間の変化量です。公式は下記です。超絶的に0に近い、というかもはや0という謎の極小値でもって計算することで瞬間変化量を出します。解析的にやるといろんな公式が編み出されているので真の微分が出せますが、コンピュータで公式通りにやろうとすると、謎の極小値を本当にすごい小さい値にすることになるので、誤差がでます。しかしその誤差が非常に小さいので多くの場合問題ありません。

[mathjax] $$\frac{df(x)}{dx} = \lim_{h \to 0}\frac{f(x+h) - f(x)}{h}$$

Pythonだと下記になります。

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

これよりも誤差を小さくする方法は下記です。

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

サンプル

import numpy as np
import matplotlib.pyplot as plt

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

def sample_func(x):
    return x**2

x = np.arange(-7.0, 7.0, 0.1)
x2 = np.arange(-1.0, 7.0, 0.1)
k = 2

y = sample_func(x)
d = numerical_diff(sample_func, k)
y2 = d * x2 + sample_func(k) - d*k

plt.plot(x, y)
plt.plot(x2, y2)
plt.show()