|
| 1 | +-- Newton (Raphson) root finding algorithm implementation |
| 2 | +-- See : http://en.wikipedia.org/wiki/Newton%27s_method |
| 3 | + |
| 4 | +-- Fuzzy equality test |
| 5 | +local function fuzzyEqual(a, b, eps) |
| 6 | + local eps = eps or 1e-4 |
| 7 | + return (math.abs(a - b) < eps) |
| 8 | +end |
| 9 | + |
| 10 | +-- Evaluates the derivative of function f at x0 |
| 11 | +-- Uses Newton's centered slope approximation |
| 12 | +local function drvMid(f, x0, initStep) |
| 13 | + local step = initStep or 0.1 |
| 14 | + local incr1, incr2 = (f(x0 + step) - f(x0 - step)) / (2 * step) |
| 15 | + repeat |
| 16 | + incr2 = incr1 |
| 17 | + step = step / 2 |
| 18 | + incr1 = (f(x0 + step) - f(x0 - step)) / (2 * step) |
| 19 | + until fuzzyEqual(incr1, incr2) |
| 20 | + return incr1 |
| 21 | +end |
| 22 | + |
| 23 | +-- Find a zero for a given function f |
| 24 | +-- f : the equation, to be solved (f(x) = 0) |
| 25 | +-- initStep : (optional) initial value for iterations |
| 26 | +-- eps : (optional) accuracy parameter for convergence |
| 27 | +-- returns : a zero for the function f |
| 28 | +return function(f, initStep, eps) |
| 29 | + local next_x = initStep or 0 |
| 30 | + local prev_x |
| 31 | + repeat |
| 32 | + prev_x = next_x |
| 33 | + next_x = next_x - (f(next_x) / drvMid(f, next_x)) |
| 34 | + until fuzzyEqual(next_x, prev_x, eps) |
| 35 | + return next_x |
| 36 | +end |
0 commit comments