function goldenRatioMinimum(fn, a, b, ε) {
ε = ε || 1e-8;
var φ = (-1 + Math.sqrt(5)) / 2;
var x1 = a + (1 - φ) * (b - a);
var x2 = b - (1 - φ) * (b - a);
var A = fn(x1);
var B = fn(x2);
while(b - a > ε) {
if(A < B) {
b = x2;
x2 = x1;
B = A;
x1 = a + (1 - φ) * (b - a);
A = fn(x1);
} else {
a = x1;
x1 = x2;
A = B;
x2 = b - (1 - φ) * (b - a);
B = fn(x2);
}
}
var x = (a + b) / 2;
x = Math.abs(x) < 1e-6 ? 0 : x;
return {
x: x,
y: fn(x)
}
}
// Пример
var result = goldenRatioMinimum(function(x) { return x * x - 4 }, 0, 1);
alert("Минимум функции f(x) = x² - 4 на отрезке [-1; 1] находится в точке x = " + result.x + " и f(" + result.x + ") = " + result.y);