Effacer les filtres
Effacer les filtres

How to test whether a function has roots within a given range?

6 vues (au cours des 30 derniers jours)
Joseph
Joseph le 12 Fév 2024
Commenté : Torsten le 12 Fév 2024
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

Réponse acceptée

Torsten
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)))
I = 1×6
1 17 33 50 66 83
F(x(I))
ans = 1×6
0 0.0951 -0.1893 0.0951 -0.1893 0.0951
F(x(I+1))
ans = 1×6
0.1893 -0.0951 0.0000 -0.0951 0.0000 -0.0951

Plus de réponses (1)

Walter Roberson
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
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.

Connectez-vous pour commenter.

Tags

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by