How to test whether a function has roots within a given range?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to create a program that applies the newton raphson method to find the roots of a function within a given range. I'm writing a test to check if there are any roots within the given range, by checking for a sign change in the variable F_X. Please could someone explain how I can test whether roots exist within the given range? I've added my code so far.
%function definitiion
str = input('Give an equation in x: ','s') ;
f = inline(str,'x') ;
%range
xmin = input('What is the minimum value of X? ');
xmax = input('What is the maximum value of X? ');
x = linspace(xmin,xmax);
F_X = feval(f,x);
% check for sign change in F_X
SignF_X = sign(F_X);
%check signs to test for roots
0 commentaires
Réponse acceptée
Torsten
le 12 Fév 2024
F = @(x) sin(x);
xmin = 0;
xmax = 6*pi;
x = linspace(xmin,xmax);
Fx = F(x);
I = find(diff(sign(Fx)))
F(x(I))
F(x(I+1))
Plus de réponses (1)
Walter Roberson
le 12 Fév 2024
has_root = SignF_X(1:end) ~= SignF_X(2:end);
However, your approach is flawed.
Suppose the input function is a sufficiently high-frequency sine wave, then evaluating at linspace might happen to get results that are all on one side of zero even though there are lots of zero crossings.
Or suppose the equation is a simple x^2 - delta where delta is small compared to the difference between linspace entries: there is a (pair of) zeros for the function but you would not be able to detect it.
Any approach that looks for sign changes over a grid will fail on some equations.
1 commentaire
Torsten
le 12 Fév 2024
Any approach that looks for sign changes over a grid will fail on some equations.
Yes, but it's still the safest method for most equations if the grid is set quite fine.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!