原代码
数学思路
point类
//文件1,类的定义,point.h
#ifndef _POINT_H
#define _POINT_H
class Point{
public:
Point(float x=0, float y=0) :x(x), y(y) {
}
float GetX() const {
return x;}
float GetY() const {
return y;}
private:
float x,y;
};
#endif
主函数
//主函数,main.cpp
#include "point.h"
#include <iostream>
#include <cmath>
using namespace std;
//直线线性拟合,points 为各点,nPoint 为点数
float lineFit(const Point points[], int nPoint) //友元函数体
{
float avgX=0,avgY=0; //定义变量
float lxx=0,lyy=0,lxy=0;
for(int i=0;i<nPoint;i++) //计算X、Y的平均值
{
avgX+=points[i].GetX()/nPoint;
avgY+=points[i].GetY()/nPoint;
}
for(int i=0;i<nPoint;i++) //计算Lxx、Lyy和Lxy
{
lxx+=(points[i].GetX()-avgX)*(points[i].GetX()-avgX);
lyy+=(points[i].GetY()-avgY)*(points[i].GetY()-avgX);
lxy+=(points[i].GetX()-avgX)*(points[i].GetY()-avgY);
}
cout<<"This line can be fitted by y=ax+b."<<endl;
cout<<"a="<<lxy/lxx; //输出回归系数a
cout<<" b="<<avgY-lxy*avgX/lxx<<endl; //输出回归系数b
return float(lxy/sqrt(lxx*lyy));