Skip to content

Instantly share code, notes, and snippets.

@Yonaba
Last active December 28, 2015 04:49
Show Gist options
  • Save Yonaba/7445033 to your computer and use it in GitHub Desktop.
Save Yonaba/7445033 to your computer and use it in GitHub Desktop.
Newton Raphson Solver
local DOUBLE_IEEE_ACCURACY = 1e-8
local function areFuzzyEqual(a, b, accuracy)
return (math.abs(a-b) < (accuracy or DOUBLE_IEEE_ACCURACY))
end
local function derivative(f, x0, accuracy)
local h = 0.1
local xL, xR = x0 - h, x0 + h
local tAccr = (f(xR) - f(xL))/(2*h)
repeat
local tAccr2 = tAccr
h = h/2
xL, xR = x0 - h, x0 + h
tAccr = (f(xR) - f(xL))/(2*h)
until areFuzzyEqual(tAccr, tAccr2, accuracy)
return tAccr
end
local function newtonRaphsonSolver(f, x0, accuracy)
local xi, xi_1
repeat
xi_1 = xi
xi = xi - (f(x0)/derivative(f, x0))
until areFuzzyEqual(xi, xi_1, accuracy)
return xi
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment