bisection method convergence graph not smooth

1 view (last 30 days)
Okay guys first post on here.
I have just started to use matlab and one of my first tasks is to write code for bisection method and calculate the change in the c value for each iteration (and f(c)). We are doing it for the equation f(x)=tan(x)-x. Now I'm pretty confident I have the bisection method running fairly well but when it comes to storing the change in c value for each iteration it comes undone. The goal is to graph the change in c again iterations as it converges to zero so I want to store each change in c value in a matrix and plot them against each other. I'm meant to get 2 curves that are very similar but one of the curves is all wonky and I can't seem to find the issue after days of frustration. The graph I am getting is attatched and what I need is for both the curves to be smooth. As you can see my fcmat curve is quite wonky. Hopefully this makes sense, I'll post my code below, hopefully I've commented enough so it makes sense. If anyone could tell me where I am going wrong that would be great because it all makes sense to me.
a=-1;
b=0.9;
n=input('Number of Iterations ');
tol=abs(10^-1600);
%------ Setting up xpoints for plotting
xpoints=(1:n);
%-------- For loop calculates fa, c and fc for the start of each iteration
for I=1:n;
fa=tan(a)-a;
c=(a+b)/2;
fc=tan(c)-c;
fac=fa*fc;
%---------If statement or assignmining if c=b and c=a and assigning the difference in c values (abs(c-c2)) to a matrix for both cases (if fac<0 or >0)
if fac<0
b=c;
c2=(a+b)/2;
cmat(I)=abs(c-c2);
fc2=tan(c2)-c2;
fcmat(I)=abs(fc-fc2);
else a=c;
c2=(a+b)/2;
cmat(I)=abs(c-c2);
fc2=tan(c2)-c2;
fcmat(I)=abs(fc-fc2);
%-------- If statement terminating when fc<tol -->> some set tolerance
if abs(fc)<abs(tol)
disp('Tolerance reached, Iterations completed ')
disp(I)
break
end
end
end
loglog(xpoints,cmat,'r',xpoints,fcmat,'g')
legend('cmat','fcmat')
c;
fc;
  2 Comments
Walter Roberson
Walter Roberson on 13 Aug 2015
I notice that you only check tolerance if fac >= 0 . Is there a reason for that?

Sign in to comment.

Answers (0)

Categories

Find more on Discrete Data Plots 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!