📄 曲线拟合.txt
字号:
#include<iostream.h>
#include<math.h>
#define MN 6 //观测值组数
#define ML 3 //多项式项数
double X[]={0,1,2,3,4,5},Y[]={2.08,7.68,13.8,27.1,40.8,61.2};//观测数值
double C[MN][ML]; //矛盾方程组系数矩阵
double A[ML][ML+1]; //正规方程组增广矩阵
void f0() //求矛盾方程组系数矩阵C
{
cout<<'\n'<<"矛盾方程组的系数矩阵为:"<<'\n';
cout<<"---------------------------"<<'\n';
cout<<"C[i][j]";
for(int k=0;k<ML;k++)
cout<<'\t'<<k;
cout<<'\n'<<"---------------------------"<<'\n';
double temp;
for(int i=0;i<MN;i++)
{
cout<<" "<<i;
temp=1; //系数矩阵第一列为1
for(int j=0;j<ML;j++)
{
C[i][j]=temp;
temp*=X[i];
cout<<'\t'<<C[i][j];
}
cout<<'\n';
}
cout<<"---------------------------"<<'\n';
}
void f1() //求正规方程组增广矩阵
{
cout<<'\n'<<"正规方程组的增广矩阵为:"<<'\n';
cout<<"----------------------------------------"<<'\n';
cout<<"CT*C";
for(int k=0;k<ML;k++)
cout<<'\t'<<" "<<k;
cout<<'\t'<<"CT*Y";
cout<<'\n'<<"----------------------------------------"<<'\n';
double temp;
for(int i=0;i<ML;i++) //ML为列
{
for (int j=0;j<ML;j++)
{
temp=0;
for(int k=0;k<MN;k++) //MN为行
temp+=C[k][i]*C[k][j];//CT*C
A[i][j]=temp;
A[j][i]=temp;
}
}
for(i=0;i<ML;i++) //CT*Y
{
temp=0;
for(int k=0;k<MN;k++)
temp+=C[k][i]*Y[k];
A[i][ML]=temp;
}
for(i=0;i<ML;i++)
{
cout<<" "<<i;
for(int j=0;j<=ML;j++)
{
cout<<'\t'<<" "<<A[i][j];
}
cout<<'\n';
}
cout<<"----------------------------------------"<<'\n';
}
void f2(int k) //选列主元
{
double temp;
for (int i=k+1;i<ML;i++)
{
if(fabs(A[i][k])>fabs(A[k][k]))
{
for(int j=k;j<=ML;j++)
{
temp=A[k][j];
A[k][j]=A[i][j];
A[i][j]=temp;
}
}
}
}
void f3() //约当消去法
{
cout<<'\n'<<"约当消去法求正规方程组的增广矩阵:"<<'\n';
cout<<"----------------------------------------"<<'\n';
cout<<"A[i][j]";
for(int k=0;k<ML;k++)
cout<<'\t'<<k;
cout<<'\t'<<"Y[i]";
cout<<'\n'<<"----------------------------------------"<<'\n';
double temp;
for(int i=0; i<ML;i++)
{
f2(i); //选列主元
temp=A[i][i];
for(int j=0;j<=ML;j++)//ML+1列
A[i][j]/=temp;
for(int k=0;k<ML;k++)
{
if(k==i)
continue;
temp=A[k][i];
for(j=i;j<=ML;j++)
A[k][j]-=temp*A[i][j];
}
}
for(i=0;i<ML;i++)
{
cout<<" "<<i;
for(int j=0;j<=ML;j++)
{
cout<<'\t'<<A[i][j];
}
cout<<'\n';
}
cout<<"----------------------------------------"<<'\n';
}
void main()
{
f0();
f1();
f3();
for(int i=0;i<ML;i++)
cout<<'\n'<<" " <<'A'<<i<<'='<<A[i][ML]<<'\n';
cout<<"----------------"<<'\n';
}
(1)利用多项式拟合的两个模块程序求解下题:
给出 x、y的观测值列表如下:
x 0 1 2 3 4 5
y 2.08 7.68 13.8 27.1 40.8 61.2
试利用二次多项式y=a0+a1x+a2x2进行曲线拟合。
(1)多项式拟合方法:假设我们收集到两个相关变量x、y的n对观测值列表:
x x0 x1 x2 x3 x4 x5
y y0 y1 y2 y3 y4 y5
我们希望用m+1个基函数w0(x),w1(x),…,wm(x)的一个线形组合
y=a0w0(x)+a1w1(x)+…+amwm(x)
来近似的表达x、y间的函数关系,我们把几对测量值分别代入上式中,就可以得到一个线形方程组:
a0w0(x0)+a1w1(x0)+…+amwm(x0)=y0
a0w0(x1)+a1w1(x1)+…+amwm(x1)=y1
… …
a0w0(xn)+a1w1(xn)+…+amwm(xn)=yn
只需要求出该线形方程组的最小二乘解,就能得到所构造的的多项式的系数,从而解决问题。
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -