0%

计算方法实验/实验七

实验七

最佳平方逼近

【作业内容】: 在区间$[5,10]$上,对函数$f(x)=lnx$进行最佳一次和二次平方逼近(小数点后保留8位小数)。

【作业要求】:

  1. 具体计算出f(x)的最佳一次逼近多项式$y=P_1 (x)$和最佳二次逼近多项式$y=P_2(x)$

  2. 画出$y=f(x)$,$y=P_1 (x)$和$y=P_2(x)$的图像,进行比较。

求最佳逼近多项式系数

定义在OptimalSquareApproximation.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
% 最佳平方逼近

% f为待逼近函数,n为最佳逼近多项式次数,[left,right]为积分区间
function x = OptimalSquareApproximation(f,n,left,right)
format long;
% 定义x^i * f(x)的匿名函数用于后续求积分
rightfun = @(i) (@(x) x.^i .* f(x));

% 定义左端的系数矩阵基本形式
leftfun = @(i,j) (@(x) x.^i .* x.^j);

% 定义线性方程的左右两端矩阵
A = zeros(n+1,n+1);
b = zeros(n+1,1);


for p = 0:n
for q = 0:n
A(p+1, q+1) = integral(leftfun(p,q),left,right); % 计算左端系数矩阵的每一项积分
end
% 计算右端矩阵的每一项
b(p+1,1) = integral(rightfun(p),left,right);
end

x = inv(A)*b;
% disp(x);

end

绘制一次,二次最佳逼近多项式以及原函数图像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
format long;
% g = @(x) sqrt(1 + x.^2);
% m = OptimalSquareApproximation(g,1,0,1);

f = @(x) log(x);
one = OptimalSquareApproximation(f,1,5,10); % 获取最佳一次逼近多项式系数
two = OptimalSquareApproximation(f,2,5,10); % 获取最佳二次逼近多项式系数
% 对多项式系数按从高次到低次排列
one = flip(one);
two = flip(two);


x0 = 5:0.01:10;
y0 = f(x0);
figure;
plot(x0,polyval(m,x0))



plot(x0,polyval(one,x0),'g',x0,polyval(two,x0),'b',x0,y0)
xlabel('x轴');
ylabel('y轴');
legend('最佳一次逼近多项式','最佳二次逼近多项式','原曲线');


format short;

绘制图像

实验七结果