Filter löschen
Filter löschen

repeat while loop with new boundary for x

4 Ansichten (letzte 30 Tage)
Quoc Khang Doan
Quoc Khang Doan am 27 Mär. 2021
Kommentiert: Walter Roberson am 27 Mär. 2021
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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 27 Mär. 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 Kommentare
Quoc Khang Doan
Quoc Khang Doan am 27 Mär. 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 am 27 Mär. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by