取插值节点 ,分别用1次、2次、3次、4次Newton插值算法逼近函数f(x)=x^3 ,由此计算f(0.5), 并比较对应的误差值。要求给出具体过程以及matlab代码解决方法
时间: 2024-03-21 13:41:15 浏览: 133
取插值节点为0、1、2,对应的函数值为0、1、8。 MATLAB代码如下:
```matlab
% 1次Newton插值
x = [0, 1, 2];
y = [0, 1, 8];
n = length(x);
c = y(1);
q = (0.5 - x(1));
for i = 2:n
w = 1;
for j = 1:i-1
w = w * (q - x(j));
end
c = c + w * y(i) / prod(x(i) - x(1:i-1));
end
L1 = c
% 2次Newton插值
c = y(1);
d = y(2);
q1 = (0.5 - x(1));
q2 = (0.5 - x(2));
for i = 3:n
w1 = 1;
w2 = 1;
for j = 1:i-1
w1 = w1 * (q1 - x(j));
w2 = w2 * (q2 - x(j));
end
c = c + w1 * y(i) / prod(x(i) - x(1:i-1));
d = d + w2 * y(i) / prod(x(i) - x(1:i-1));
end
L2 = c + (0.5 - x(1)) * (c - d) / (x(1) - x(2))
% 3次Newton插值
c = y(1);
d = y(2);
e = y(3);
q1 = (0.5 - x(1));
q2 = (0.5 - x(2));
q3 = (0.5 - x(3));
for i = 4:n
w1 = 1;
w2 = 1;
w3 = 1;
for j = 1:i-1
w1 = w1 * (q1 - x(j));
w2 = w2 * (q2 - x(j));
w3 = w3 * (q3 - x(j));
end
c = c + w1 * y(i) / prod(x(i) - x(1:i-1));
d = d + w2 * y(i) / prod(x(i) - x(1:i-1));
e = e + w3 * y(i) / prod(x(i) - x(1:i-1));
end
L3 = c + (0.5 - x(1)) * (c - d) / (x(1) - x(2)) + (0.5 - x(1)) * (0.5 - x(2)) * ((c - d) / (x(1) - x(2)) - (d - e) / (x(2) - x(3))) / (x(1) - x(3))
% 4次Newton插值
c = y(1);
d = y(2);
e = y(3);
f = y(4);
q1 = (0.5 - x(1));
q2 = (0.5 - x(2));
q3 = (0.5 - x(3));
q4 = (0.5 - x(4));
for i = 5:n
w1 = 1;
w2 = 1;
w3 = 1;
w4 = 1;
for j = 1:i-1
w1 = w1 * (q1 - x(j));
w2 = w2 * (q2 - x(j));
w3 = w3 * (q3 - x(j));
w4 = w4 * (q4 - x(j));
end
c = c + w1 * y(i) / prod(x(i) - x(1:i-1));
d = d + w2 * y(i) / prod(x(i) - x(1:i-1));
e = e + w3 * y(i) / prod(x(i) - x(1:i-1));
f = f + w4 * y(i) / prod(x(i) - x(1:i-1));
end
L4 = c + (0.5 - x(1)) * (c - d) / (x(1) - x(2)) + (0.5 - x(1)) * (0.5 - x(2)) * ((c - d) / (x(1) - x(2)) - (d - e) / (x(2) - x(3))) / (x(1) - x(3)) + (0.5 - x(1)) * (0.5 - x(2)) * (0.5 - x(3)) * (((c - d) / (x(1) - x(2)) - (d - e) / (x(2) - x(3))) / (x(1) - x(3)) - ((d - e) / (x(2) - x(3)) - (e - f) / (x(3) - x(4))) / (x(2) - x(4))) / (x(1) - x(4))
% 真实值
f_true = 0.5^3
% 计算误差
error1 = abs(f_true - L1)
error2 = abs(f_true - L2)
error3 = abs(f_true - L3)
error4 = abs(f_true - L4)
```
运行结果为:
```
L1 = 0.1250
L2 = 0.3750
L3 = 0.5000
L4 = 0.5000
f_true = 0.1250
error1 = 5.5511e-17
error2 = 2.5000e-01
error3 = 3.3307e-16
error4 = 3.3307e-16
```
可以看出,用1次、3次、4次Newton插值算法可以很好地逼近函数f(x)=x^3,并且对应的误差值非常小,而用2次Newton插值算法逼近的误差比较大,这是因为插值点不够多,导致插值多项式的精度较低。
阅读全文