使用最小二乘法求九组数据的二次多项式、三次多项式拟合曲线c++代码
时间: 2023-08-07 09:05:20 浏览: 106
以下是使用最小二乘法求九组数据的二次多项式、三次多项式拟合曲线的 C++ 代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 最小二乘法求解系数
void leastSquares(int n, double x[], double y[], double a[]) {
double sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0, sumX3 = 0.0, sumX4 = 0.0, sumX2Y = 0.0;
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumX2 += x[i] * x[i];
sumX3 += x[i] * x[i] * x[i];
sumX4 += x[i] * x[i] * x[i] * x[i];
sumX2Y += x[i] * x[i] * y[i];
}
double D = n * sumX2 * sumX4 + 2 * sumX * sumX3 * sumX2 - sumX2 * sumX2 * sumX2 - n * sumX3 * sumX3 - sumX * sumX * sumX4;
double Da = sumY * sumX2 * sumX4 + sumXY * sumX3 * sumX2 + sumX * sumX2Y * sumX3 - sumX2Y * sumX2 * sumX2 - sumXY * sumX2 * sumX - sumY * sumX3 * sumX3;
double Db = n * sumXY * sumX4 + sumY * sumX3 * sumX2 + sumX * sumX2 * sumX2Y - sumX2Y * sumX * sumX2 - sumY * sumX2 * sumX4 - n * sumX * sumX3;
double Dc = n * sumX2 * sumX2Y + sumX * sumXY * sumX4 + sumY * sumX2 * sumX3 - sumX2 * sumXY * sumX3 - sumX * sumX2Y * sumX2 - sumY * sumX * sumX4;
a[0] = Da / D;
a[1] = Db / D;
a[2] = Dc / D;
}
int main() {
// 九组数据
double x[9] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0};
double y[9] = {2.1, 7.7, 13.6, 27.2, 40.9, 61.1, 81.6, 102.4, 131.9};
// 二次多项式拟合
double a2[3];
leastSquares(9, x, y, a2);
cout << "二次多项式拟合方程:y = " << a2[2] << "x^2 + " << a2[1] << "x + " << a2[0] << endl;
// 三次多项式拟合
double a3[4];
double x2[9], y2[9];
for (int i = 0; i < 9; i++) {
x2[i] = x[i] * x[i];
y2[i] = y[i] * y[i];
}
leastSquares(9, x, y2, a3);
double b[3];
for (int i = 0; i < 3; i++) {
b[i] = a3[i] * a3[i];
}
double c[4];
c[0] = a2[2];
c[1] = a2[1];
c[2] = a2[0];
c[3] = 0.0;
for (int i = 0; i < 3; i++) {
c[3] += b[i];
}
double tmp[4];
leastSquares(4, x, c, tmp);
cout << "三次多项式拟合方程:y = " << tmp[3] << "x^3 + " << tmp[2] << "x^2 + " << tmp[1] << "x + " << tmp[0] << endl;
return 0;
}
```
其中,`leastSquares` 函数实现了最小二乘法求解系数的过程。在 `main` 函数中,我们使用这个函数分别求出了二次多项式和三次多项式的系数,并输出了拟合方程。需要注意的是,在求解三次多项式系数时,我们先对原始数据进行了一次平方,然后再使用最小二乘法求解系数。最后,我们将二次多项式和三次多项式的系数结合起来,得到了三次多项式的拟合方程。
阅读全文