输入九组数据,使用最小二乘法求一组数据的二次多项式、三次多项式拟合曲线c++代码
时间: 2024-03-10 17:48:27 浏览: 66
C++的最小二乘法实现曲线拟合
5星 · 资源好评率100%
以下是C++代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const int N = 9; // 数据个数
const int M = 3; // 多项式次数
int main()
{
double x[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // x 坐标
double y[N] = {0.53, 0.91, 1.75, 3.14, 4.74, 6.87, 9.12, 11.58, 13.97}; // y 坐标
// 二次多项式拟合
double A[M+1][M+2] = {0}; // 增广矩阵
for (int i = 0; i <= M; i++)
{
for (int j = 0; j <= M; j++)
{
for (int k = 0; k < N; k++)
{
A[i][j] += pow(x[k], i+j);
}
}
}
for (int i = 0; i <= M; i++)
{
for (int k = 0; k < N; k++)
{
A[i][M+1] += y[k] * pow(x[k], i);
}
}
// 高斯消元求解增广矩阵
for (int i = 0; i <= M; i++)
{
double t = A[i][i];
for (int j = i; j <= M+1; j++)
{
A[i][j] /= t;
}
for (int j = i+1; j <= M; j++)
{
t = A[j][i];
for (int k = i; k <= M+1; k++)
{
A[j][k] -= t * A[i][k];
}
}
}
double B[M+1] = {0}; // 多项式系数
for (int i = M; i >= 0; i--)
{
B[i] = A[i][M+1];
for (int j = i+1; j <= M; j++)
{
B[i] -= A[i][j] * B[j];
}
}
cout << "二次多项式拟合结果:" << endl;
cout << "c2 = " << B[2] << ", c1 = " << B[1] << ", c0 = " << B[0] << endl;
// 三次多项式拟合
double C[M+1][M+2] = {0}; // 增广矩阵
for (int i = 0; i <= M; i++)
{
for (int j = 0; j <= M; j++)
{
for (int k = 0; k < N; k++)
{
C[i][j] += pow(x[k], i+j);
}
}
}
for (int i = 0; i <= M; i++)
{
for (int k = 0; k < N; k++)
{
C[i][M+1] += y[k] * pow(x[k], i);
}
}
// 高斯消元求解增广矩阵
for (int i = 0; i <= M; i++)
{
double t = C[i][i];
for (int j = i; j <= M+1; j++)
{
C[i][j] /= t;
}
for (int j = i+1; j <= M; j++)
{
t = C[j][i];
for (int k = i; k <= M+1; k++)
{
C[j][k] -= t * C[i][k];
}
}
}
double D[M+1] = {0}; // 多项式系数
for (int i = M; i >= 0; i--)
{
D[i] = C[i][M+1];
for (int j = i+1; j <= M; j++)
{
D[i] -= C[i][j] * D[j];
}
}
cout << "三次多项式拟合结果:" << endl;
cout << "c3 = " << D[3] << ", c2 = " << D[2] << ", c1 = " << D[1] << ", c0 = " << D[0] << endl;
return 0;
}
```
执行该程序后,输入九组数据,即可得到一组数据的二次多项式和三次多项式拟合结果。
阅读全文