C++实现最小二乘法求数据的斜率,相关系数,截距

详细的代码如下所示:

static void LeastSquaresFitting(int nData[],int nLen,double &a,double &b,double &r)
{
	double av_x,av_y; //声明变量
	double L_xx,L_yy,L_xy;
	double *fData = new double[nLen];	
	//变量初始化
	av_x = 0; //X的平均值
	av_y = 0; //Y的平均值
	L_xx = 0; //Lxx
	L_yy = 0; //Lyy
	L_xy = 0; //Lxy
	int i = 0;
	for(i = 0; i < nLen; i++) //计算X、Y的平均值
	{
		fData[i] = log((double)nData[i]);
		av_x += i;
		av_y += fData[i];
	}
	av_x = av_x/nLen;
	av_y = av_y/nLen;
	
	for(i = 0; i < nLen; i++) //计算Lxx、Lyy和Lxy
	{
		L_xx += (i-av_x)*(i-av_x);
		L_yy += (fData[i]-av_y)*(fData[i]-av_y);
		L_xy += (i-av_x)*(fData[i]-av_y);
	}
	a = L_xy/L_xx; //斜率
	b = av_y-L_xy*av_x/L_xx; //截距
	r = double(L_xy/sqrt(L_xx*L_yy)); //相关系数r	
	r *= r;
	delete fData;
}

 

展开阅读全文

没有更多推荐了,返回首页