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 ビュー (過去 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 Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by