
clc
clear
f = @(x) 0.1*x.^3 + 20*cos(x) + 10;
h = 0.1; %Шаг производной
df = @(x) (f(x+h) - f(x-h))/(2*h); %Вычисление производной
tol = 1e-6; %Точность
iterlimit = 200; %Предел итераций
ezplot(f); %Создание графика
grid on
x0 = [];
function[root, iter] = newton(f, df, x0, tol, iterlimit);
iter = 0;
while abs(f(x0)) > tol && iter < iterlimit
x1 = x0 - f(x0)/df(x0);
x0 = x1;
iter = iter + 1;
end
if abs(f(x0)) <= tol
root = x0;
else
root = [];
end
end
for x = -6.5:h:6.5
if f(x)*f(x+h) < 0
x0 = [x0, x];
end
end
tic
for i=1:length(x0);
[root, iter] = newton(f, df, x0(i), tol, iterlimit);
if ~isempty(root);
disp(['Корень при х0 = ', num2str(x0(i))]);
disp(['х = ', num2str(root)]);
disp(['f(x) = ', num2str(f(root))]);
disp(['Количество итераций = ', num2str(iter)]);
disp(' ');
else
disp('Превышено число итераций');
end
end
toc
clear
f = @(x) 0.1*x.^3 + 20*cos(x) + 10;
h = 0.1; %Шаг производной
df = @(x) (f(x+h) - f(x-h))/(2*h); %Вычисление производной
tol = 1e-6; %Точность
iterlimit = 200; %Предел итераций
ezplot(f); %Создание графика
grid on
x0 = [];
function[root, iter] = newton(f, df, x0, tol, iterlimit);
iter = 0;
while abs(f(x0)) > tol && iter < iterlimit
x1 = x0 - f(x0)/df(x0);
x0 = x1;
iter = iter + 1;
end
if abs(f(x0)) <= tol
root = x0;
else
root = [];
end
end
for x = -6.5:h:6.5
if f(x)*f(x+h) < 0
x0 = [x0, x];
end
end
tic
for i=1:length(x0);
[root, iter] = newton(f, df, x0(i), tol, iterlimit);
if ~isempty(root);
disp(['Корень при х0 = ', num2str(x0(i))]);
disp(['х = ', num2str(root)]);
disp(['f(x) = ', num2str(f(root))]);
disp(['Количество итераций = ', num2str(iter)]);
disp(' ');
else
disp('Превышено число итераций');
end
end
toc