线性最小二乘拟合程序
某系统输入输出呈线性关系:Y=aX + b,但参数a、b未知。通过对系统输入(X)和输出(Y)的数据统计,应用最小二乘估计确定a和b的值。现有一次测量活动得到如下10组[X,Y]数据:
[1, 9.762]
[2, 12.719]
[3, 15.497]
[4, 18.143]
[5, 18.982]
[6, 21.008]
[7, 24.596]
[8, 26.285]
[9, 29.369]
[10, 31.17]
请编程实现:输入上述测量数据后,输出参数a和b的值,以及10个测量值的离差(离差:应用拟合函数计算的Y值与测量的Y值之差)。
程序要求:
(1) 一切计算过程全部用程序实现,具备通用性,即可以拟合任意Y=aX + b型线性关系;
(2) 计算完成后,可将数据导入Excel显示测量数据(散点)和拟合后的直线,并将该显示图形加入到结题报告中;
(3) 输出数据可以输出到文本文件,
尽量简单一点,不需要太复杂,太精简
https://blog.csdn.net/yangziluomu/article/details/103503387
这里有现成代码
如有帮助,望采纳
//Linear Fit
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
int i,j,k,n;
cout<<"\nEnter the no. of data pairs to be entered:\n"; //To find the size of arrays
cin>>n;
double x[n],y[n],a,b;
cout<<"\nEnter the x-axis values:\n"; //Input x-values
for (i=0;i<n;i++)
cin>>x[i];
cout<<"\nEnter the y-axis values:\n"; //Input y-values
for (i=0;i<n;i++)
cin>>y[i];
double xsum=0,x2sum=0,ysum=0,xysum=0; //variables for sums/sigma of xi,yi,xi^2,xiyi etc
for (i=0;i<n;i++)
{
xsum=xsum+x[i]; //calculate sigma(xi)
ysum=ysum+y[i]; //calculate sigma(yi)
x2sum=x2sum+pow(x[i],2); //calculate sigma(x^2i)
xysum=xysum+x[i]*y[i]; //calculate sigma(xi*yi)
}
a=(n*xysum-xsum*ysum)/(n*x2sum-xsum*xsum); //calculate slope
b=(x2sum*ysum-xsum*xysum)/(x2sum*n-xsum*xsum); //calculate intercept
double y_fit[n]; //an array to store the new fitted values of y
for (i=0;i<n;i++)
y_fit[i]=a*x[i]+b; //to calculate y(fitted) at given x points
cout<<"S.no"<<setw(5)<<"x"<<setw(19)<<"y(observed)"<<setw(19)<<"y(fitted)"<<endl;
cout<<"-----------------------------------------------------------------\n";
for (i=0;i<n;i++)
cout<<i+1<<"."<<setw(8)<<x[i]<<setw(15)<<y[i]<<setw(18)<<y_fit[i]<<endl;//print a table of x,y(obs.) and y(fit.)
cout<<"\nThe linear fit line is of the form:\n\n"<<a<<"x + "<<b<<endl; //print the best fit line
return 0;
}