format long
l=-1;
u=2;
fprintf('Press 1 for bisection \n Press 2 for secant \n');
ch=input('Enter choice: ');
f = @(x) sin(x)-x;
e=1e-6;
if(ch==1)
a=l;
b=u;
iter = 0;
if f(a)*f(b)>=0
disp('No Root')
else
prev = (a+b)/2;
p=a;
while (abs(p-prev)>e)
prev=p;
iter =iter+ 1;
p = (a+b)/2;
if f(p) == 0
break;
end
if f(a)*f(p)<0
b = p;
else
a = p;
end
if(iter==100)
disp('the required accuracy is not reached in 50 iterations');
end
end
end
disp('Root by bisection is');
disp(p);
else
x0=l;
x1=u;
i=0;
imax=200;
x2=x1+1;
flag=1;
while (abs(x2-x1)>e)
if(i~=0)
x1=x2;
end
x2=x1-((f(x1)/(f(x1)-f(x0)))*(x1-x0));
x0=x1;
i=i+1;
if(i==200)
disp('the required accuracy is not reached in 100 iterations');
flag=0;
end
end
disp('Root using secant is');
if(flag==1)
root=x2
else
root=[];
end
end
Comments
Leave a comment