最小二乘法及其c++的实现

//最小二乘法的实现
#include<iostream>
#include<cmath>
#include "source.h"
#define Length 10
using namespace std;
double fun(int n, double array[Length][Length])
{
	int ii, jj, k, u;
	int iter = 0;  //记录行变换的次数(交换)
	double det1 = 1, yin;

	for (ii = 0; ii < n; ii++)
	{
		for (k = ii + 1; k < n; k++)
		{
			yin = -1 * array[k][ii] / array[ii][ii];

			for (u = 0; u < n; u++)
			{
				array[k][u] = array[k][u] + array[ii][u] * yin;
			}
		}
	}
	for (ii = 0; ii < n; ii++)  //求对角线的积 即 行列式的值
		det1 = det1 * array[ii][ii];
	//行变换偶数次符号不变
	if (iter % 2 == 1)
		det1 = -det1;
	return (det1);
}
void  LeastSquareMethod(int n,int m, double* x, double* y) {
	int i, j;
	double temp[Length][Length];
	double d[Length], arr[Length][Length];
	double tempsumx, tempsumy;
	double sumx[Length] = { 0.0 }, sumy[Length] = { 0.0 };
	for (i = 0; i <2*m; i++) {
		tempsumx = 0.0;
		tempsumy = 0.0;
		for (j = 0; j < n; j++) {
			tempsumx += pow(x[j], i + 1);
			tempsumy += pow(x[j], i) * y[j];
		}
		sumx[i] = tempsumx;
		sumy[i] = tempsumy;
	}
	int a=0;
	//上三角
	for (i = 1; i < m + 1; i++) {
		temp[0][0] = n;
		for (j = 0; j <= i; j++) {
			temp[j][i - j] = sumx[i - 1];
			a = i - 1;
		}
	}
	//下三角
	for (j = 1; j <= m; j++) {
		for (i = 0; i <= m - j; i++) {
			temp[i + j][m - i] = sumx[a + j];
		}
	}
	//临时赋值
	for (i = 0; i <= m; i++) {
		for (j = 0; j <= m; j++) {
			arr[i][j] = temp[i][j];
		}
	}
	for (i = 0; i <= m; i++) {
		for (j = 0; j <= m; j++) {
			arr[j][i] = sumy[j];
		}
		d[i + 1] = fun(m+1, arr);//求行列式的值
		for (int p = 0; p <= m; p++) {
			for (int q = 0; q <= m; q++) {
				arr[p][q] = temp[p][q];//恢复被改变过的arr
			}
		}
	}
	d[0] = fun(m + 1, temp);
	double z[Length];
	for (i = 0; i <= m; i++) {
		z[i] = d[i + 1] / d[0];
	}
	char cha = '+';
	cout << "拟合数据的" << m << "次多项式为:P" << m << "(x)=" << z[0];
	for (i = 1; i <= m; i++) {
		if (z[i] < 0)
			cha = ' ';
		cout << cha << z[i] << "x^" << i;
	}
	cout << endl;
}
int main() {
	int n, m, xi, i;
	double x[Length], y[Length];
	cout << "请输入x和f(x)的个数:";
	cin >> n;
	cout << "----------录入数据----------\n" << endl;
	for (i = 0; i < n; i++) {
		cout << "x[" << i << "]=";
		cin >> x[i];
		cout << "y[" << i << "]=";
		cin >> y[i];
	}
	cout << "\n----------录入完毕----------" << endl;
	cout << "请输入所求多项式的次数:";
	cin >> m;
	LeastSquareMethod(n, m, x, y);
	system("pause");
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值