1. 已知函数在下列各点的值为
0.2 |
0.4 |
0.6 |
0.8 |
1.0 |
|
0.98 |
0.92 |
0.81 |
0.64 |
0.38 |
用插值法对数据进行拟合,要求给出Lagrange插值多项式和Newton插值多项式的表达式,并计算插值多项式在点的值。
程序:
x=[0.2 0.4 0.6 0.8 1.0];
y=[0.98 0.92 0.81 0.64 0.38];
x0=[0.2 0.28 0.44 0.76 1 1.08];
[f,f0]=Lagrange(x,y,x0)
function [f,f0] = Lagrange(x,y,x0)
%求已知数据点的Lagrange插值多项式f,并计算插值多项式f在数据点x0的函数值f0
syms t;
n = length(x);
f = 0.0;
for i = 1:n
l = y(i);
for j = 1:i-1
l = l*(t-x(j))/(x(i)-x(j));
end;
for j = i+1:n
l = l*(t-x(j))/(x(i)-x(j));
end;
f = f + l;
simplify(f);
if(i==n)
f0 = subs(f,\'t\',x0);
f = collect(f);
f = vpa(f,6);
end
end
结果:
>> Untitled3
f =
- 0.520833*t^4 + 0.833333*t^3 - 1.10417*t^2 + 0.191667*t + 0.98
f0 =
[ 49/50, 60137/62500, 56377/62500, 42497/62500, 19/50, 15017/62500]
牛顿:
%y为对应x的值,A为差商表,C为多项式系数,L为多项式
%X为给定节点,Y为节点值,x为待求节点
function[y,A,C,L] = newton(X,Y,x,M)
n = length(X);
m = length(x);
for t = 1 : m
z = x(t);
A = zeros(n,n);
A(:,1) = Y\';
s = 0.0; p = 1.0; q1 = 1.0; c1 = 1.0;
for j = 2 : n
for i = j : n
A(i,j) = (A(i,j-1) - A(i-1,j-1))/(X(i)-X(i-j+1));
end
q1 = abs(q1*(z-X(j-1)));
c1 = c1 * j;
end
C = A(n, n); q1 = abs(q1*(z-X(n)));
for k = (n-1):-1:1
C = conv(C, poly(X(k)));
d = length(C);
C(d) = C(d) + A(k,k);
end
y(t) = polyval(C,z);
end
L = poly2sym(C);
x=[0.2 0.4 0.6 0.8 1.0];
y=[0.98 0.92 0.81 0.64 0.38];
x0=[0.2 0.28 0.44 0.76 1 1.08];
m=1;
[y,A,C,L]=newton(x,y,x0,m)
结果:
y =
0.9800 0.9622 0.9020 0.6800 0.3800 0.2403
A =
0.9800 0 0 0 0
0.9200 -0.3000 0 0 0
0.8100 -0.5500 -0.6250 0 0
0.6400 -0.8500 -0.7500 -0.2083 0
0.3800 -1.3000 -1.1250 -0.6250 -0.5208
C =
-0.5208 0.8333 -1.1042 0.1917 0.9800
L =
- (25*x^4)/48 + (5*x^3)/6 - (53*x^2)/48 + (23*x)/120 + 49/50
2. 在区间上分别取,用两组等距节点对Runge函数作多项式插值(Lagrange插值和Newton插值均可),要求对每个值,分别画出插值多项式和函数的曲线。
程序:
x=-1:0.2:1;
y=1./(1+25*x.^2);
x0=-1:0.01:1;
[f,f0]=Lagrange(x,y,x0)
plot(x0,f0)
结果:
f =
- 220.942*t^10 + 494.91*t^8 - 381.434*t^6 + 123.36*t^4 - 16.8552*t^2 + 1.0
3.下列数据点的插值
0.01 |
1 |
4 |
9 |
16 |
25 |
36 |
49 |
64 |
|
0.1 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
可以得到平方根函数的近似多项式, 要求用上述9个点作8次插值多项式,并在区间画出的曲线。
程序:
x=[0.01 1 4 9 16 25 36 49 64];
y=[0.1 1 2 3 4 5 6 7 8];
x0=0.01:0.1:64;;
[f,f0]=Lagrange(x,y,x0)
plot(x0,f0)
xlim([0 64]);
结果:
f =
- 2.73858e-10*t^8 + 5.6069e-8*t^7 - 0.00000453906*t^6 + 0.000186698*t^5 - 0.00418177*t^4 + 0.0510128*t^3 - 0.32628*t^2 + 1.19115*t + 0.0881211