Skip to content

Commit 689bf02

Browse files
committed
Added equation method using Newton-Raphson solver
1 parent be4b05e commit 689bf02

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

Golden_Ratio_Algorithms/Lua/Yonaba/golden_ratio.lua

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,20 @@ local function gold_number_babylonian_iteration(seed, acc)
5151
return phi
5252
end
5353

54+
-- Computes an approximate value of the Golden Ratio
55+
-- Using a Newton-Raphson solver (implemented as an external dependency)
56+
-- See: http://en.wikipedia.org/wiki/Golden_ratio#Calculation
57+
-- seed : (optional) seed to start the computation (defaults to 1)
58+
-- acc : (optional) approximation accuracy (defaults to 1E-8)
59+
-- returns : an approximation of the Golden Ratio
60+
local solve = require 'lib.newtonraphson'
61+
local function gold_number_equation(seed, acc)
62+
return solve(function(x) return x * x - x - 1 end, seed, acc)
63+
end
64+
5465
return {
5566
root = gold_number_root_iteration,
5667
fractional = gold_number_fractional_iteration,
57-
babylonian = gold_number_babylonian_iteration
68+
babylonian = gold_number_babylonian_iteration,
69+
equation = gold_number_equation,
5870
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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

Comments
 (0)