问题:用线性函数p(x)= a+ bx拟合给定数据(xi,;yi;).i= 0,1,2,…,m-1。
算法描述
(1)给已知条件(X0,y0),(X1,y1),(X2,y2),…,(Xn,yn)点进行对应的包装操作和编号处理
(2)根据最小二乘问题的正则方程组
2.1 求得 Xk 的累加和,其中k=0,1,2,…m-1
2.2求得Yk 的累加和,其中k=0,1,2…m-1
2.3 求得 Xk2 的累加和,其中k=0,1,2,…m-1
2.4 求得XkYk 的累加和,其中k=0,1,2,…m-1
(3)通过
二元一次方程组的求解即可解得对应a,b的值,然后得出结果
源程序代码及运行结果截图
#include<iostream>
#include<vector>
#include<math.h>
#include<iomanip>
#include<string>
using namespace std;
struct Point
{
Point(float x, float y) {
this->x = x;
this->y = y;
}
Point() {
}
float x; //坐标的x轴
float y; //坐标的y轴
int k = -1; //给每个已知点进行编号,表示第k个点,k = 0,1,2....n
};
//存放已知点编号完成后的动态向量
vector<Point> *vec = NULL;
/*
@param points 要初始化的已知点数组
@param len 数组长度
*/
void init(Point points[], int len)
{
vec = new vector<Point>();
for (int i = 0; i < len; i++)
{
//给每个点进行编号处理
points[i].k = i;
//将每个点放入到向量集合中
vec->push_back(points[i]);
}
}
/*
@to do: 计算X0,X1...Xn的累加结果
@return float 返回结果
*/
float getAccumulateX() {
float result = 0; //x累加的结果
vector<Point>::iterator it;
//开始迭代累加x的值
for (it = vec->begin(); it != vec->end(); it++)
{
result += (*it).x;
}
return result;
}
/*
@to do: 计算Y0,Y1...Yn的累加结果
@return float 返回结果
*/
float getAccumulateY() {
float result = 0; //y累加的结果
vector<Point>::iterator it;
//开始迭代累加y的值
for (it = vec->begin(); it != vec->end(); it++)
{
result += (*it).y;
}
return result;
}
/*
@to do: 计算X0,X1...Xn的平方累加和结果
@return float 返回结果
*/
float getAccumulateXY() {
float result = 0; //x*y累加的结果
vector<Point>::iterator it;
//开始迭代累加x*y的值
for (it = vec->begin(); it != vec->end(); it++)
{
result += (*it).y *(*it).x;
}
return result;
}
/*
@to do: 计算Y0*X0,Y1*X1...Yn*Xn的累加结果
@return float 返回结果
*/
float getXSquared() {
float result = 0; //x的平方累加的结果
vector<Point>::iterator it;
//开始迭代累加x*x的值
for (it = vec->begin(); it != vec->end(); it++)
{
result += (*it).x *(*it).x;
}
return result;
}
/*
@to do: 获取x0节点对应的朗格朗日函数值
@param X0 需要求解的x0的值
@return float 返回结果
*/
string getLinearFittingValue(int n) {
//获取X的累加和
float a1 = getAccumulateX();
//获取Y的累加和
float b1 = getAccumulateY();
//获取X平方的累加和
float c1 = getXSquared();
//获取X*Y的累加和
float d1 = getAccumulateXY();
//求得a的值
float a = (b1*c1-d1*a1) / (n*c1-a1*a1);
//求得b的值
float b = (n*d1 - a1*b1) / (n*c1 - a1 * a1);
//得出表达式
string s = to_string(a) +(b>0 ?("+"+ to_string(b)): to_string(b)) + "X";
return s;
}
int main()
{
//测试数据
Point p1(2.0f, 5.0f);
Point p2(4.0f, 3.5f);
Point p3(4.0f, 3.0f);
Point p4(4.6f, 2.7f);
Point p5(5.0, 2.4f);
Point p6(5.2f, 2.5f);
Point p7(5.6f, 2.0f);
Point p8(6.0, 1.5f);
Point p9(6.6f,1.2f);
Point p10(7.0, 1.2f);
Point points[10] = { p1,p2,p3,p4,p5,p6,p7,p8,p9,p10 };
init(points, 10);
string s = getLinearFittingValue(10);
cout << "拟合的结果为:" << s << endl;
system("pause");
return 0;
}