Golden Section
clc;
clear;
f=@(x) x.^2+2*x;
a=-3;
b=3;
error=0.8;
r=(sqrt(5)-1)/2;
x0=a;
x3=b;
x1=a+(1-r)*(b-a);
x2=a+r*(b-a);
y1=feval(f,x1);
y2=feval(f,x2);
while (x3-x0)*r>error
if y1<=y2
x3=x2;
x2=x1;
x1=x0+(1-r)*(x3-x0);
else
x0=x1;
x1=x2;
x2=x0+r*(x3-x0);
end
y1=feval(f,x1);
y2=feval(f,x2);
end
y_array=[feval(f,x0),y1,y2,feval(f,x3)];
[ymin,index]=min(y_array);
x_array=[x0,x1,x2,x3];
xmin=x_array(index);
disp(sprintf('minimum of f(x) is %5.3f that occurs at x=%5.3f\n',ymin,xmin))
clear;
f=@(x) x.^2+2*x;
a=-3;
b=3;
error=0.8;
r=(sqrt(5)-1)/2;
x0=a;
x3=b;
x1=a+(1-r)*(b-a);
x2=a+r*(b-a);
y1=feval(f,x1);
y2=feval(f,x2);
while (x3-x0)*r>error
if y1<=y2
x3=x2;
x2=x1;
x1=x0+(1-r)*(x3-x0);
else
x0=x1;
x1=x2;
x2=x0+r*(x3-x0);
end
y1=feval(f,x1);
y2=feval(f,x2);
end
y_array=[feval(f,x0),y1,y2,feval(f,x3)];
[ymin,index]=min(y_array);
x_array=[x0,x1,x2,x3];
xmin=x_array(index);
disp(sprintf('minimum of f(x) is %5.3f that occurs at x=%5.3f\n',ymin,xmin))
0 Comments:
Post a Comment
<< Home