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
0 个评论
采纳的回答
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)))
F(x(I))
F(x(I+1))
更多回答(1 个)
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
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!