I am new to MATLAB and have encountered a problem on an assignment. The assignment is to use the bisection method. My original code was:
a = -0.5;
b = 1.1;
f=@(x) x^5-2*x^4+3*x^3-2*x^2+x-1-cos(30*x);
val1 = f(a);
val2 = f(b);
p1a1 = val1*val2;
save('A1.dat','p1a1','-ascii')
%bisection
for i = 0:100
c = (a+b)/2;
if f(c) >= -0.000000001 && f(c) <= 0.000000001
answer = c;
elseif f(c) > 0
b = c;
else a = c;
end
end
answer = c;
save('A2.dat','answer','-ascii')
However, I needed to count the number of iterations it took, so I changed the second part of the code (after "bisection") to:
tolerance = 0.000000001;
count = 0;
c =(a+b)/2;
while abs(f(c))>tolerance
count=count+1;
if f(c) > 0
b = c;
else
a = c;
end
end
answer = c;
Where c would show the zero of the function, within the prescribed tolerance. The new code won't run however, and I cannot seem to figure out where i have gone wrong. Apologies if it is something simple
<=would probably be better than<, given that (by definition)epsis the smallest representable value. Alsoeps = 2.2e-16on my machine, the tolerance used in the question should be of no concern for numerical accuracy.