% Find max of f(x) = -3*x^2 + 21.6*x + 1, x in [0,25] using Golden section method
clear all
close all

t = 0.1;
a = 0;
b = 25;
r = (sqrt(5) - 1)/2;
n = ceil(log(t/(b-a))/log(r));

x1 = a + (1-r)*(b-a);
x2 = a + r*(b-a);

fx1 = -3*x1^2 + 21.6*x1 + 1;
fx2 = -3*x2^2 + 21.6*x2 + 1;

for k=1:n

    if fx1 >= fx2
        a = a;
        b = x2;
        x2 = x1;
        fx2 = fx1;
        
        x1 = a + (1-r)*(b-a);
        fx1 = -3*x1^2 + 21.6*x1 + 1;
    else
        a = x1;
        b = b;
        x1 = x2;
        fx1 = fx2;
        
        x2 = a + r*(b-a);
        fx2 = -3*x2^2 + 21.6*x2 + 1;
    end
end

x_s = (a+b)/2
Max = -3*x_s^2 + 21.6*x_s + 1


exact_x = 3.6
exact_max = -3*exact_x^2 + 21.6*exact_x + 1
