repeat while loop with new boundary for x

1 view (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 27 Mar 2021
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 Comments
Quoc Khang Doan
Quoc Khang Doan on 27 Mar 2021
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 on 27 Mar 2021
"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

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!