# 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 visualizzazione (ultimi 30 giorni)
SELAM HAILE il 21 Lug 2021
Risposto: Shubham Khatri il 28 Lug 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 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Walter Roberson il 21 Lug 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.

Accedi per commentare.

### Risposte (1)

Shubham Khatri il 28 Lug 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
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Parallel for-Loops (parfor) in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by