Last active
December 28, 2015 04:49
-
-
Save Yonaba/7445033 to your computer and use it in GitHub Desktop.
Newton Raphson Solver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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