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

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

 Accepted Answer

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

More Answers (1)

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 Comment

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.

Sign in to comment.

Categories

Find more on Mathematics in Help Center and File Exchange

Products

Release

R2022b

Tags

Asked:

on 12 Feb 2024

Commented:

on 12 Feb 2024

Community Treasure Hunt

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

Start Hunting!