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

3 次查看(过去 30 天)
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

采纳的回答

Alagu Sankar Esakkiappan
编辑:Alagu Sankar Esakkiappan 2021-12-10
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by