Bisection method while loop not iterating, only gives the first answer.
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Walter Roberson
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!