MATLAB Answers

secant method, when I run my code I keep getting an error saying output 1 the root is being numerically incorrect. can I get help?

3 views (last 30 days)
SELAM HAILE
SELAM HAILE on 21 Jul 2021
Answered: Shubham Khatri on 28 Jul 2021
function [xroot,residual,ea,iterCount]=student_solution(fun,xi,es,max_it,varargin)
fun=@(x) sin(2*x)-tan(x/4)
if(nargin<3)
e=1e-5;
else
e=es;
end
x0=xi(1);
x1=xi(2);
i=0;
if(nargin<4)
imax=30;
else
imax=max_it;
end
x2=x1+1;
flag=1;
while (abs(fun(x2))>e)
if(i~=0)
x1=x2;
end
x2=x1-((fun(x1)/(fun(x1)-fun(x0)))*(x1-x0));
x0=x1;
i=i+1;
if(i==imax)
flag=0;
break;
end
end
if(flag==1)
xroot=x2;
else
xroot=[];
end
iterCount=i;
residual=fun(xroot);
ea=abs((x2-x1)/(x2));
end
  1 Comment
Walter Roberson
Walter Roberson on 21 Jul 2021
How are you running the code? I suspect that you are pressing the green Run button which is wrong as the xi parameter must be passed in.

Sign in to comment.

Answers (1)

Shubham Khatri
Shubham Khatri on 28 Jul 2021
Hello,
I was not able to reproduce the issue on my end but as Walter pointed out, you need to call the function and pass the values of all the input parameters. I tried it at my end and the code works perfectly. Take a look at the code below.
a=2;
b=[3,5,2];
c=4;
d=5;
[u,v,w,z]=student_solution(a,b,c,d)
function [xroot,residual,ea,iterCount]=student_solution(fun,xi,es,max_it,varargin)
fun=@(x) sin(2*x)-tan(x/4)
if(nargin<3)
e=1e-5;
else
e=es;
end
x0=xi(1);
x1=xi(2);
i=0;
if(nargin<4)
imax=30;
else
imax=max_it;
end
x2=x1+1;
flag=1;
while (abs(fun(x2))>e)
if(i~=0)
x1=x2;
end
x2=x1-((fun(x1)/(fun(x1)-fun(x0)))*(x1-x0));
x0=x1;
i=i+1;
if(i==imax)
flag=0;
break;
end
end
if(flag==1)
xroot=x2;
else
xroot=[];
end
iterCount=i;
residual=fun(xroot);
ea=abs((x2-x1)/(x2));
end
Hope it helps

Community Treasure Hunt

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

Start Hunting!

Translated by