function Newton :
function [] = Newton(x0, n)
disp(strcat('x0 :', num2str(x0))); % 打印初值
m = 1;
while m <= n
p = [1, 0, 0, -6]; % f(x) = x^3 - 6
p1 = polyder(p); % f'(x)
x0 = x0 - polyval(p,x0)/polyval(p1,x0); % x1 = x0 - f(x0)/f'(x0)
disp(strcat('x', num2str(m), ' :', num2str(x0, '%.9f'))); % 打印
m = m + 1;
end
end
runNewton.m
format long;
Newton(2, 5); % 初值 x0=2 ,迭代计算5次
计算结果:
>> runNewton
x0 :2
x1 :1.833333333
x2 :1.817263545
x3 :1.817120604
x4 :1.817120593
x5 :1.817120593