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?

조회 수: 1 (최근 30일)
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
Walter Roberson
Walter Roberson 2021년 7월 21일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Shubham Khatri
Shubham Khatri 2021년 7월 28일
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

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by