MATLAB Answers

Bisection method while loop not iterating, only gives the first answer.

21 views (last 30 days)
Sylvina Barreto
Sylvina Barreto on 24 Sep 2020
Answered: Walter Roberson on 25 Sep 2020
Hello,
To start, I would like to say that I'm pretty new to Matlab and coding in general. I've tried to solve my issue for a while now and I guess it might be better to ask somebody that already knows :)
So, I wrote a matlab function of the bisection method and I have to use a while loop that iterates with new values of a and b until the length (|a-b|) < tolerance but my loop is not iterating and I don't understand why. Please help me!
This is what I did:
function [y,iterations] = bisection(f,a,b,tolerance);
f = @(x) 3*cos(4*x);
a = 0;
b = 1;
FA = f(a);
FB = f(b);
if FA*FB > 0 %FA and FB must have opposite signs.
fprintf('The opposite sign requirement is not met, we need new values of a and b')
end
if FA == 0 | FB == 0 %Neither FA or FB can be 0 because that would be a root.
fprintf('the function evaluated at a or b is a root')
end
tolerance = 1^(-6);
length = abs(a-b);
iterations = 0;
while length > tolerance
c = FA+FB/2; %Find the midsection
FC = f(c);
if FC == 0 %Same as above, FC can't be 0, because that means we found a root.
fprintf('The midsection is a root')
break
end
%Updating values of a and b accordingly.
if FC*FA>0
c=a;
else
c=b;
end
length; %calculates the new length
iterations = iterations + 1;
end
y = (a+b)/2
iterations
end

  3 Comments

Walter Roberson
Walter Roberson on 24 Sep 2020
length; %calculates the new length
No it doesn't. That just brings the value of length to attention, then discards it without doing anything with it because there is a semi-colon at the end that tells it not to output anything.
Sylvina Barreto
Sylvina Barreto on 25 Sep 2020
I see, could you provide some more insight on how to solve it then? If I remove the semicolon and add the formula to that line nothing different happens :/

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 25 Sep 2020
if FC*FA>0
c=a;
else
c=b;
end
Why are you assigning to c there? You never use c afterwards. If you made it to another iteration of the loop, the next loop would do
c = FA+FB/2; %Find the midsection
which would overwrite c based upon FA and FB, neither of which are changed in your loop.
c = FA+FB/2; %Find the midsection
That line has multiple errors. You need to think a lot more about that line.

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by