How do I make my function identify the root of a function within an interval?
Información
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Mostrar comentarios más antiguos
function [xsol,d] = mysolve(f,x0,x1,tol)
%This function will solve an equation, f(x) = 0
% that has a root between x0 and x1.
%Use:
% [xsol,d] = mysolve(f,x0,x1,tol)
%where: f = function, x0 is one fence, x1, is the other fence,
% tol is the tolerance for stopping.
% xsol is the estimate of the root and d is the error bound.
%
while abs(x1 - x0) > tol
xm = (x0+x1)/2;
if f(xm)*f(x1)>0
x1 = xm;
elseif f(xm)*f(x0)>0
x0 = xm;
end
end
xsol = (x0+x1)/2;
d = abs(x1-x0)/2;
end
This function works “most of the time” but it may not work in special cases as in the following example: [xsol,d] = mysolve(@(x) x,-1,1,1.E-4)
How do I fix this? I NEED to use this approach.
Respuestas (1)
David Goodmanson
el 25 de Oct. de 2018
0 votos
Hi NS,
You need to take a look at how this algorithm could fail. If f(x0) and f(x1) have opposite signs, then one or the other of your two 'if' conditions must be true, unless f(xm) = 0 in which case neither is true. In your non-working example, that's what happens. So you need to trap for f(xm) = 0 and do something about it, such as stop at that point. While you are at it it wouldn't hurt to verify that the function has opposite signs at the end points when you start out.
La pregunta está cerrada.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!