def solve(f, ini = 0, dx = 1.0e-8, eps = 1.0e-8, times = 100)
res = ini
times.times do
x = res
y = f.call(res)
return res if y.abs <= eps
res = linear_solve(*point_slope_to_linear_function(x, y, diff(f, x, dx)))
end
return
end
def diff(f, x, dx = 1.0e-8)
d1 = (f.call(x) - f.call(x-dx)) / dx
d2 = (f.call(x+dx) - f.call(x)) / dx
(d1+d2) / 2
end
def linear_solve(k, b)
-b/k
end
def point_slope_to_linear_function(x, y, k)
[k, y-x*k]
end
def solve(f, ini = 0, dx = 1.0e-8, eps = 1.0e-8, times = 100)
res = ini
times.times do
x = res
y = f.call(res)
return res if y.abs <= eps
res = linear_solve(*point_slope_to_linear_function(x, y, diff(f, x, dx)))
end
return
end
def diff(f, x, dx = 1.0e-8)
d1 = (f.call(x) - f.call(x-dx)) / dx
d2 = (f.call(x+dx) - f.call(x)) / dx
(d1+d2) / 2
end
def linear_solve(k, b)
-b/k
end
def point_slope_to_linear_function(x, y, k)
[k, y-x*k]
end
使用Newton法。