Effacer les filtres
Effacer les filtres

Quadratic Approximation Method to find the maximum of f(x). got into an infinite loop

3 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Alagu Sankar Esakkiappan
Alagu Sankar Esakkiappan le 10 Déc 2021
Modifié(e) : Alagu Sankar Esakkiappan le 10 Déc 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.

Plus de réponses (0)

Catégories

En savoir plus sur Systems of Nonlinear Equations dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by