Моя программа работает нормально, я хочу добавить графическое представление, чтобы показать сходимость метода Ньютона в этом примере:
function NewtonRoot(f, df, x_ns, numIt, delta, epsilon)
%NEWTONROOT is a scheme for finding the root of f(x) = 0.
% Arguments definations:
% NewtonRoot(f, df, x_ns, numIt, delta, epsilon)
% f: the function f(x)
% df: dervative of f(x)
% x_ns: The first estimate
% numIt: The maximum number of iterations
% delta: Tolerance in two successive iterations
% epsilon: Tolerance in function at numerical solution
if abs(df(x_ns)) <= 10E-6
disp(['The derivative of the function in the vicinity of solution', ...
'is too close to zero.'])
end
% Using the Newton/Raphson's equation to find the first estimate
x_ns1 = x_ns -f(x_ns)/df(x_ns);
x_nsOld = x_ns1;
counter = 0; % Counter, controles if the maximum number of iterations not
% exceeds the pre-defined value.
errIteration = delta + 1;
errFunction = epsilon + 1;
% The header of the output table
disp(' ');
disp(['Iteration X_NS solution f(X_NS) Derivative f(X_NS) ',...
'Error iteration']);
% Iteration
while abs(errIteration) >= delta || abs(errFunction) >= epsilon % Two
% stoping criteria ...
x_nsNew = x_nsOld - f(x_nsOld)/df(x_nsOld);
errIteration = abs(x_nsNew-x_nsOld)/x_nsOld; % Error in two successive
% iteration
errFunction = abs(f(x_nsNew));% Error in function/tolerance in function
tangent = @(x) df(x_nsOld)*x +f(x_nsOld)-df(x_nsOld)*x_nsOld; % tangent
% line in every step
figure(1)
fplot(f, [8, 11],'blue');
hold on
fplot(0, 'red');
pause(0.5)
hold on
fplot(tangent, [8, 11]);
pause(1)
x_nsOld = x_nsNew;
counter = counter + 1;
if counter == numIt
disp('The maximum number of iterations has been reached.')
break
end
fprintf('%6i %11.6f %16.6f %15.6f %15.6f\n', ...
counter, x_nsNew, f(x_nsNew), df(x_nsNew), errIteration);
end
end
Я установил диапазон в этом примере как [8, 11], потому чтоя уже знаю, что функция имеет по крайней мере реальную нулевую точку в этом интервале, но графическое представление все еще неясно, касательные линии расположены слишком близко друг к другу, поэтому слишком трудно различить линии. И этот диапазон работает только дляуникальная функция, как я могу обобщить диапазон для любой произвольной функции?
![enter image description here](https://i.stack.imgur.com/CM28e.png)