「.NET 開発基盤部会 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
df(x) yの増量 f(x+h) - f(x) f(x+h) - f(x) ── = ─── = lim ────── = lim ────── dx xの増量 h→0 (x+h) - (x) h→0 h
式の展開によって微分を求める(誤差がない)。
2 y = x
df(x) yの増量 (x+h)^2 - x^2 (x^2+2hx+h^2) - (x^2) ── = ─── = lim ────── = lim ────────── dx xの増量 h→0 (x+h) - (x) h→0 h
dy 2hx+h^2 ── = lim ──── = lim 2x+h = 2x dx h→0 h h→0
計算によって微分を求める(誤差がある)。
"""This is a test program.""" import numpy as np import matplotlib.pyplot as plt def numerical_diff(f, x): """数値微分""" h = 1e-4 # 微小な値hとして1の-4乗を用いる return (f(x + h) - f(x - h)) / (2 * h) # 前方差分から中心差分にして誤差減 def function_1(x): """f(x)=0.01x^2+0.1x""" return 0.01 * x ** 2 + 0.1 * x X=5 print("X=" + str(X) + " : " + str(numerical_diff(function_1, X))) X=10 print("X=" + str(X) + " : " + str(numerical_diff(function_1, X))) X = np.arange(0.0, 20.0, 0.1) Y = function_1(X) plt.xlabel("x") plt.ylabel("f(x)") plt.plot(X, Y) plt.show()
X=5 : 0.1999999999990898 X=10 : 0.2999999999986347
y = 4x1^3 + 2x2^2 + 1
∂y ── = 12x1^2 ∂x1
2 2 f(x0, x1) = x0 + x1
"""This is a test program.""" import numpy as np def function_2(x): """f(x0, x1) = x0^2 + x1^2""" return x[0] ** 2 + x[1] ** 2 # or return np.sum(x ** 2)
df(x0, x1) ───── = 2 * x0 dx0 df(x0, x1) ───── = 2 * x1 dx1
numerical_diff"""This is a test program.""" import numpy as np def numerical_diff(f, x): """数値微分""" h = 1e-4 # 微小な値hとして1の-4乗を用いる return (f(x + h) - f(x - h)) / (2 * h) # 前方差分から中心差分にして誤差減 def function_tmp1(x0): """x0=3, x1=4 の場合の x0 に対する偏微分用""" return x0 ** 2 + 4.0 ** 2 def function_tmp2(x1): """x0=3, x1=4 の場合の x1 に対する偏微分用""" return 3.0 ** 2.0 + x1 ** 2 print(numerical_diff(function_tmp1, 3.0)) print(numerical_diff(function_tmp2, 4.0))
6.00000000000378 (2 * x0 = 2 * 3 = 6) 7.999999999999119 (2 * x1 = 2 * 4 = 8)