Bisection method while loop not iterating, only gives the first answer.
이전 댓글 표시
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
Walter Roberson
2020년 9월 24일
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
2020년 9월 25일
Walter Roberson
2020년 9월 25일
You should be recalculating length at that point.
답변 (1개)
Walter Roberson
2020년 9월 25일
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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!