MATLAB代码实现,寻找函数最小值。
主程序如下,main.c
clc
clear
close all
%% 黄金节点法估计最小值
a = [];
b = [];
lambda = [];
miou = [];
k = 1;
a(1) = 0;
b(1) = 1;
deta = 0.00001;
%% 循环
lambda(k) = a(k)+0.382*(b(k)-a(k));
miou(k) = a(k)+0.618*(b(k)-a(k));
while k<=100
if fun( lambda(k) )>fun( miou(k) )
if b(k)-lambda(k)<=deta
disp(miou(k))
k = k+1;
break;
else
a(k+1) = lambda(k);
b(k+1) = b(k);
lambda(k+1) = miou(k);
miou(k+1) = a(k+1)+0.618*(b(k+1)-a(k+1));
k = k+1;
end
else
if b(k)-lambda(k)<=deta
disp(lambda(k))
k = k+1;
break;
else
a(k+1) = a(k);
b(k+1) = miou(k);
miou(k+1) = lambda(k);
lambda(k+1) = a(k+1)+0.382*(b(k+1)-a(k+1));
k = k+1;
end
end
end
子函数代码:
function [output] = fun(x)
output = exp(-x)+x^2;
end