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

6 次查看(过去 30 天)
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

采纳的回答

Torsten
Torsten 2024-2-12
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

更多回答(1 个)

Walter Roberson
Walter Roberson 2024-2-12
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 个评论
Torsten
Torsten 2024-2-12
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.

请先登录,再进行评论。

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by