使用最小二乘法拟合直线 C++

随着的斜率和截距,计算所述估计值的标准误差,和相关系数。
2025-01-04 02:25:34
推荐回答(2个)
回答1:

//point.h
class Point //Point类的声明
{
public: //外部接口
Point(float xx=0, float yy=0) {X=xx;Y=yy;}
float GetX() {return X;}
float GetY() {return Y;}
friend float linefit(Point l_point[], int n_point); //友元函数
//int型变量为点数
private: //私有数据成员
float X,Y;
};
//End of point.h
//main.cpp
#include
#include
#include "point.h"
using namespace std;
float linefit(Point l_point[], int n_point) //友元函数体
{
float av_x,av_y; //声明变量
float L_xx,L_yy,L_xy;
//变量初始化
av_x=0; //X的平均值
av_y=0; //Y的平均值
L_xx=0; //Lxx
L_yy=0; //Lyy
L_xy=0; //Lxy
for(int i=0;i{
   av_x+=l_point[i].X/n_point;
   av_y+=l_point[i].Y/n_point;
}
for(i=0;i{
   L_xx+=(l_point[i].X-av_x)*(l_point[i].X-av_x);
   L_yy+=(l_point[i].Y-av_y)*(l_point[i].Y-av_y);
   L_xy+=(l_point[i].X-av_x)*(l_point[i].Y-av_y);
}
cout<<"This line can be fitted by y=ax+b."<cout<<"a="<cout<<" b="<return float(L_xy/sqrt(L_xx*L_yy)); //返回相关系数r
}
int main()
{
Point l_p[10]={Point(6,10),Point(14,20),Point(26,30),
   Point(33,40),Point(46,50),Point(54,60),Point(67,70),
   Point(75,80),Point(84,90),Point(100,100)}; //初始化数据点
float r=linefit(l_p,10); //进行线性回归计算
cout<<"Line coefficient r="<}

回答2:

这是通过调试的程序,可以试试
#include
#include
#include
using namespace std;

class LeastSquare{
double a, b;
public:
LeastSquare(const vector& x, const vector& y)
{
double t1=0, t2=0, t3=0, t4=0;
for(int i=0; i {
t1 += x[i]*x[i];
t2 += x[i];
t3 += x[i]*y[i];
t4 += y[i];
}
a = (t3*x.size() - t2*t4) / (t1*x.size() - t2*t2);
//b = (t4 - a*t2) / x.size();
b = (t1*t4 - t2*t3) / (t1*x.size() - t2*t2);
}

double getY(const double x) const
{
return a*x + b;
}

void print() const
{
cout<<"y = "< }

};

int main(int argc, char *argv[])
{
if(argc != 2)
{
cout<<"Usage: DataFile.txt"< return -1;
}
else
{
vector x;
ifstream in(argv[1]);
for(double d; in>>d; )
x.push_back(d);
int sz = x.size();
vector y(x.begin()+sz/2, x.end());
x.resize(sz/2);
LeastSquare ls(x, y);
ls.print();

cout<<"Input x:\n";
double x0;
while(cin>>x0)
{
cout<<"y = "< cout<<"Input x:\n";
}
}
}