repeat while loop with new boundary for x

4 次查看(过去 30 天)
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 中查找有关 Particle Swarm 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by