Quadratic Approximation Method to find the maximum of f(x). got into an infinite loop
Ältere Kommentare anzeigen
clear all;
clc;
syms x;
fprintf('QUADRATIC APPROXIMATION METHOD\n\n');
f=log(x)*sin(x^2);
x0=1;
x1=1.8;
x2=2;
err=10;
epsilon=1e-11;
i=0;
fprintf(' i x0 x1 x2 x3\n');
while err>epsilon
f0=double(subs(f,x,x0));
f1=double(subs(f,x,x1));
f2=double(subs(f,x,x2));
x3=(((x1^2-x2^2)*f0+(x2^2-x0^2)*f1+(x0^2-x1^2)*f2))/(2*((x1-x2)*f0+(x2-x0)*f1+(x0-x1)*f2));
f3=double(subs(f,x,x3));
if x0<x3 && x3<x1
if f3<f1
x0new=x3;
x1new=x1;
x2new=x2;
elseif f3>f1
x0new=x0;
x1new=x3;
x2new=x1;
end
elseif x1<x3 && x3<x2
if f3<=f1
x0new=x0;
x1new=x1;
x2new=x3;
elseif f3>f1
x0new=x1;
x1new=x3;
x2new=x2;
end
else
fprintf('x0 is outside of [x0,x2]\n');
fprintf('x0=%.30f\n',x0);
fprintf('x1=%.30f\n',x1);
fprintf('x2=%.30f\n',x2);
fprintf('x3=%.30f\n',x3);
end
fprintf('%2d %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f %5.5f\n',i,x0,x1,x2,x3,f0,f1,f2,f3);
err=abs(x3-x1);
x0=x0new;
x1=x1new;
x2=x2new;
i=i+1;
end
xmax=x3;
fmax=double(subs(f,x,xmax));
fprintf('\nTherefore, f(x) maximum at x=%5.5f with the function value f(x)=%5.5f.\n',xmax,fmax);clear all;
I tried to find max with quadratic approach but it got into an infinite loop what do you think is wrong
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!