repeat while loop with new boundary for x

조회 수: 1 (최근 30일)
Quoc Khang Doan
Quoc Khang Doan 2021년 3월 27일
댓글: Walter Roberson 2021년 3월 27일
function [r] = myroots(x,y,tol)
a = x(1);
b = x(end);
fprintf('Starting interval is from %f to %f \n', a, b)
error = b - a;
while abs(error) > tol
c = (a+b)/2;
if y(a)*y(c) < 0
b = c;
fprintf('New interval is from %f to %f \n', a, b)
error = b - a;
elseif y(b)*y(c) < 0
a = c;
fprintf('New interval is from %f to %f \n', a, b)
error = b - a;
elseif y(b)*y(c) > 0 && y(a)*y(c) > 0
a = c;
fprintf('New interval is from %f to %f \n', a, b)
error = b - a;
end
end
r = c;
end
Im trying to write a script to find root of a function y using the bisection method, this works as intended for small range of x (only one root within the interval). But when there're multiple roots (for function such as y = cos(x) or y = sin(x), etc) I only manage to get one root over a larger range of x (interval that covers multiple root), is there a way to rerun the loop again with new interval boundary for x? Example: after first run i found the highest root for x = 0:0.1:10, new interval to rerun with be x = 0:0.1:(highest root), so on and so on.
Thank you

채택된 답변

Walter Roberson
Walter Roberson 2021년 3월 27일
Yes, of course you could program a loop like that -- but how do you know when to stop?
elseif y(b)*y(c) > 0 && y(a)*y(c) > 0
What happens if none of the if/elseif are true? For example what if y( c) is 0 exactly?
error = b - a;
That isn't the error! That is the length of the segment.
  댓글 수: 2
Quoc Khang Doan
Quoc Khang Doan 2021년 3월 27일
so i need an elseif statement for when y( c) = 0, such as:
...
elseif y(c) == 0
break
end
and fix error to (b-a)/a?
Walter Roberson
Walter Roberson 2021년 3월 27일
"error" for a root finder is usually abs(f(c)), but with code built-in to ensure that you do not take too many iterations.
But it is also sometimes reasonable to stop if the length of the segment is getting very small. But you would typically prefer a relative measure rather than an absolute measure. Length of the current segment relative to the original segment length perhaps. Or if you are close to 0 in the search then it might be reasonable to be expecting to find a root at 1e-50

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by