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?

2 views (last 30 days)
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

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

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!