微分(前進差分)


今回は微分をやってみた。計算自体は定義に沿ってやるだけなのでそんなに難しくない。ただ、どのくらい小さい数で割るか結果が違ってきてしまうので本当は注意しないといけない。次のサイトが参考になる。
http://next1.cc.it-hiroshima.ac.jp/MULTIMEDIA/numeanal1/node19.html
第69回 微分・積分の数学 数値微分 [前編] :はじめMath! Javaでコンピュータ数学|gihyo.jp … 技術評論社
第70回 微分・積分の数学 数値微分 [中編] :はじめMath! Javaでコンピュータ数学|gihyo.jp … 技術評論社

import math

def bibun(x):
	h = 1.0e-10
	return (f(x + h) - f(x)) / h

def f(x):
	return math.sin(x) + 3 * math.cos(x) - x ** 2

def main():
	f = open("plot.dat", 'w')
	x = 0
	while x <= math.pi * 8:
		ans = bibun(x)
		f.write('%f %f\n' % (x, ans))
		x += 0.1
	f.close()

if __name__ == '__main__':
	main()


作られたplot.datをgnuplotで描いてみるとこんな感じになる。



ちなみに元の関数はこんな感じ。



今回、hの値は適当に小さい数を入れた。誤差とかはあまり考えていない……