微分(中心差分)
前進差分に続いて今度は中心差分をやってみた。
import math def central_difference(x, h): return (f(x + h) - f(x - h)) / (2 * h) #前進差分との違いはここ def f(x): return math.sin(x) def output(l, filename): f = open(filename, 'w') for i in l: f.write('%f %f\n' % (i[0], i[1])) f.close() def main(): x = 0.0 h = 0.0001 ans = [] while x <= math.pi * 2: f1 = central_difference(x, h) ans.append([x, f1]) x += 0.001 output(ans, 'output.dat') if __name__ == '__main__': main()
一応こんなグラフができる。