前進差分, 中央差分, 後進差分, Richardson補外を用いたNewton法プログラム
# -*- coding: utf-8 -*-
# h = 0.00048828125
h = 0.001
def function_f(x):
return x * x - 5.0
# 前進差分
def zenshin_dif(x_v):
return x_v - function_f(x_v) / ((function_f(x_v + h) - function_f(x_v)) / h)
# 前進差分のRichardson補外
def zenshin_richard_dif(x_v):
temp1 = (function_f(x_v + h) - function_f(x_v))/h
temp2 = (1/2.0) * ((function_f(x_v + (2 * h)) - function_f(x_v))/(2 * h))
romberg1 = (temp1 - temp2)/(1 - 1/2.0)
return x_v - function_f(x_v) / romberg1
# 中央差分
def chuo_dif(x_v):
return x_v - function_f(x_v) / ((function_f(x_v + h) - function_f(x_v - h)) / (2.0 * h))
# 中央差分のRichardson補外
def chuo_richard_dif(x_v):
temp1 = (function_f(x_v + h) - function_f(x_v - h))/(2 * h)
temp2 = (1/4.0) * ((function_f(x_v + (2*h)) - function_f(x_v - (2*h))) / (4*h))
romberg1 = (temp1 - temp2)/(1 - 1/4.0)
return x_v - function_f(x_v) / romberg1
# 後進差分
def koshin_dif(x_v):
return x_v - function_f(x_v) / ((function_f(x_v) - function_f(x_v - h)) / h)
# 後進差分のRichardson補外
def koshin_richard_dif(x_v):
temp1 = (function_f(x_v + (-1*h)) - function_f(x_v))/(-1*h)
temp2 = (1/2.0) * ((function_f(x_v + (-2 * h)) - function_f(x_v))/(-2 * h))
romberg1 = (temp1 - temp2)/(1 - 1/2.0)
return x_v - function_f(x_v) / romberg1
# ステップの繰り返し
def iter(x_init):
x_v = x_init
for iter in range(0, 20):
print x_v
# x_v = zenshin_dif(x_v)
# x_v = zenshin_richard_dif(x_v)
# x_v = chuo_dif(x_v)
# x_v = chuo_richard_dif(x_v)
x_v = koshin_dif(x_v)
# x_v = koshin_richard_dif(x_v)
iter(0.01)