[数值分析]直线拟合的最小二乘法

[数值分析]直线拟合的最小二乘法

[数值分析]直线拟合的最小二乘法_第1张图片
[数值分析]直线拟合的最小二乘法_第2张图片

  • 运行示例:

[数值分析]直线拟合的最小二乘法_第3张图片

  • 源码:
#include
using namespace std;

#define MAX 10

typedef struct Point   //坐标点信息结构体
{
     
	double x;
	double y;
}point;

int main(void)
{
     
	int n;   //点的个数
	point p[MAX];   //坐标点信息结构体数组

	cout << "请输入点的个数:";
	cin >> n;

	//输入点信息,存入结构体数组
	for (int i = 1; i <= n; i++)
	{
     
		cout << "请输入第" << i << "个点的坐标:";
		cin >> p[i].x;
		cin >> p[i].y;
	}

	double N, sumX, sumY, sumX2, sumXY;   //分别表示N,∑x,∑y,∑x²,∑xy
	double a, b;   //拟合直线系数、常数项

	//赋初值
	N = n;
	sumX = sumY = sumX2 = sumXY = 0;

	//计算系数
	for (int i = 1; i <= n; i++)
	{
     
		sumX += p[i].x;
		sumY += p[i].y;
		sumX2 += p[i].x * p[i].x;
		sumXY += p[i].x * p[i].y;
	}

	//输出一元二次方程
	cout << "\n一元二次方程方程如下:" << endl;
	if (sumX > 0)  //控制输出 + - 号
	{
     
		cout << N << " * a + " << sumX << " = " << sumY << endl;
	}
	else
	{
     
		cout << "\n" << N << " * a " << sumX << " = " << sumY << endl;
	}
	
	cout << sumX << " * a + " << sumX2 << " = " << sumXY << endl;

	//根据以上定义,原一元二次方程变为以下形式
	//N * a + sumX * b = sumY;
	//sumX * a + sumX2 * b =sumXY;
	//则可解出a,b,得到拟合直线的方程

	b = (sumXY * N - sumX * sumY) / (sumX2 * N - sumX * sumX);
	a = (sumY / N) - (sumX * sumXY * N - sumX * sumX * sumY) / (sumX2 * N * N - sumX * sumX * N);

	cout << "\n拟合直线y = " << b << "x " << a << endl;

	return 0;
}

你可能感兴趣的:(#,数值分析,c++,数值分析,曲线拟合,最小二乘法,WHUT课程实验)