プログラミングで微分をするときは前方差分よりも中心差分が望ましい。理由は中心差分の方が誤差が少ないから。
import numpy as np
#前方差分
def numerical_diff_forward(f,x):
h = 1e-4
return (f(x+h) - f(x)) / h
#中央差分
def numerical_diff_center(f,x):
h = 1e-4
return (f(x+h) - f(x-h)) / (h*2)
np.float32(1e-3)
def function(x):
return 0.01*x**2+0.1*x
print(abs(0.2 - numerical_diff_forward(function,5)))
print(abs(0.2 - numerical_diff_center(function,5)))
#9.999991725240243e-07
#9.102163467389346e-13
参考
[ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装 ]