Quadratic Approximation Method to find the maximum of f(x). got into an infinite loop
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Alper Sahin
il 7 Dic 2021
Modificato: Alagu Sankar Esakkiappan
il 10 Dic 2021
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
0 Commenti
Risposta accettata
Alagu Sankar Esakkiappan
il 10 Dic 2021
Modificato: Alagu Sankar Esakkiappan
il 10 Dic 2021
Hi Alper,
I see that you're trying to find maxiumum value of a function using Quadratic approach. There is no problem per se with the implementation. Only that epsilon is initialzed to a far more optimistic value than the original convergence point for err.
Coming to your Code, I see that the value of err converges to around 1.297e-9 even after 1000 iterations. Since the condition for your while loop is ( err > epsilon ) and err never goes below epsilon ( err converged to 1.297e-9, whereas epsilon is 1e-11), you're stuck in an infinite loop. You may allow a reasonable degree of error ( say 1e-8 ) to your epsilon (or) more fine tune your algorithm if more accuracy is needed.
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Systems of Nonlinear Equations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!