golden_sector method added

This commit is contained in:
2024-11-04 20:59:32 +02:00
parent 93cf747abd
commit df7a86fae8
8 changed files with 176 additions and 7 deletions
@@ -0,0 +1,37 @@
function [a, b, k] = golden_section(fun, alpha, beta, lambda)
%
% Error checking
if lambda <= 0
error ('Convergence criteria not met')
end
% Init variables
gamma = 0.618;
a = alpha;
b = beta;
% calculate x1, x2 of the first iteration, since the following iteration
% will not require to calculate both
k=1;
x_1 = a(k) + (1 - gamma)*(b(k) - a(k));
x_2 = a(k) + gamma*(b(k) - a(k));
while b(k) - a(k) > lambda
% set new search interval
k = k + 1;
if fun(x_1) < fun(x_2)
a(k) = a(k-1);
b(k) = x_2;
x_2 = x_1;
x_1 = a(k) + (1 - gamma)*(b(k) - a(k));
else
a(k) = x_1;
b(k) = b(k-1);
x_1 = x_2;
x_2 = a(k) + gamma*(b(k) - a(k));
end
end
@@ -0,0 +1,45 @@
%
% Plot the [a,b] interval over the iterations for different lambda
% values (min, mid, max))
%
% Clear workspace and load the functions and interval
clear
addpath('..');
GivenEnv;
% * lambda_min: 0.0001
% * lambda_max: 0.1
% * N: 3 lambda values
N = 3;
lambda_min = 0.0001;
lambda_max = 0.1;
lambda = linspace(lambda_min, lambda_max, N);
k = zeros(1, N); % preallocate k
%
% * Call the golden_sector method for each lambda value for each function and
% keep the number of iterations needed.
% * Plot the [a,b] interval over iterations for each lambda for each function
%
for i = 1:length(funs)
figure;
for j = 1:N
[a, b, k(j)] = golden_section(funs{i}, a_0, b_0, lambda(j));
subplot(length(funs), 1, j)
plot(1:length(a), a, 'ob')
hold on
plot(1:length(b), b, '*r')
if j == 1
title(titles(i), 'Interpreter', 'latex')
end
xlabel("Iterations @lambda=" + lambda(j))
ylabel('[a_k, b_k]')
end
end
@@ -0,0 +1,39 @@
%
% Test the iteration needed for different lambda values.
%
% Clear workspace and load the functions and interval
clear
addpath('..');
GivenEnv;
% * lambda_min: 0.0001
% * lambda_max: 0.1
% * N: 50 points
N = 50;
lambda_min = 0.0001;
lambda_max = 0.1;
lambda = linspace(lambda_min, lambda_max, N);
k = zeros(1, N); % preallocate k
%
% * Call the golden_sector method for each lambda value for each function and
% keep the number of iterations needed.
% * Plot the iterations k(lambda) for each function
%
for i = 1:length(funs)
for j = 1:N
[a, b, k(j)] = golden_section(funs{i}, a_0, b_0, lambda(j));
end
subplot(1, length(funs), i)
plot(lambda, k, '-b', 'LineWidth', 1.0)
title(titles(i), 'Interpreter', 'latex')
xlabel('lambda')
ylabel('Iterations')
end