输入九组数据,使用最小二乘法求二次多项式、三次多项式拟合曲线c++代码
时间: 2024-03-10 10:49:27 浏览: 98
以下是使用最小二乘法求二次多项式和三次多项式拟合曲线的C++代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const int N = 9; // 数据组数
double x[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 自变量
double y[N] = {1, 4, 9, 16, 25, 36, 49, 64, 81}; // 因变量
// 求二次多项式系数
void quadratic_fit(double &a, double &b, double &c)
{
double sum_x = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0, sum_y = 0, sum_xy = 0, sum_x2y = 0;
for (int i = 0; i < N; i++)
{
double xi = x[i], yi = y[i];
sum_x += xi;
sum_x2 += xi * xi;
sum_x3 += xi * xi * xi;
sum_x4 += xi * xi * xi * xi;
sum_y += yi;
sum_xy += xi * yi;
sum_x2y += xi * xi * yi;
}
double D = N * sum_x2 * sum_x4 + 2 * sum_x * sum_x2 * sum_x3 - N * sum_x3 * sum_x3 - sum_x * sum_x4 - sum_x2 * sum_x2;
double D1 = sum_y * sum_x2 * sum_x4 + sum_x * sum_x2y * sum_x4 + sum_x2 * sum_xy * sum_x3 - sum_x3 * sum_x2y - sum_x2 * sum_x2 * sum_y - sum_x * sum_xy * sum_x2;
double D2 = N * sum_x2 * sum_x2y + sum_y * sum_x3 * sum_x3 + sum_x * sum_x3 * sum_xy - N * sum_x * sum_x2y - sum_x2 * sum_xy * sum_x3 - sum_x3 * sum_x3 * sum_y;
a = D1 / D;
b = D2 / D;
c = (sum_y - a * sum_x2 - b * sum_x3) / N;
}
// 求三次多项式系数
void cubic_fit(double &a, double &b, double &c, double &d)
{
double sum_x = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0, sum_x5 = 0, sum_x6 = 0, sum_y = 0, sum_xy = 0, sum_x2y = 0, sum_x3y = 0;
for (int i = 0; i < N; i++)
{
double xi = x[i], yi = y[i];
sum_x += xi;
sum_x2 += xi * xi;
sum_x3 += xi * xi * xi;
sum_x4 += xi * xi * xi * xi;
sum_x5 += xi * xi * xi * xi * xi;
sum_x6 += xi * xi * xi * xi * xi * xi;
sum_y += yi;
sum_xy += xi * yi;
sum_x2y += xi * xi * yi;
sum_x3y += xi * xi * xi * yi;
}
double M[4][4] = { {N, sum_x, sum_x2, sum_x3},
{sum_x, sum_x2, sum_x3, sum_x4},
{sum_x2, sum_x3, sum_x4, sum_x5},
{sum_x3, sum_x4, sum_x5, sum_x6} };
double V[4] = {sum_y, sum_xy, sum_x2y, sum_x3y};
for (int k = 0; k < 3; k++)
{
for (int i = k + 1; i < 4; i++)
{
double c = M[i][k] / M[k][k];
for (int j = k; j < 4; j++)
M[i][j] -= c * M[k][j];
V[i] -= c * V[k];
}
}
d = V[3] / M[3][3];
c = (V[2] - M[2][3] * d) / M[2][2];
b = (V[1] - M[1][2] * c - M[1][3] * d) / M[1][1];
a = (V[0] - M[0][1] * b - M[0][2] * c - M[0][3] * d) / M[0][0];
}
int main()
{
double a, b, c, d;
quadratic_fit(a, b, c);
cout << "二次多项式: y = " << a << "x^2 + " << b << "x + " << c << endl;
cubic_fit(a, b, c, d);
cout << "三次多项式: y = " << a << "x^3 + " << b << "x^2 + " << c << "x + " << d << endl;
return 0;
}
```
其中,`quadratic_fit`函数用于求解二次多项式系数,`cubic_fit`函数用于求解三次多项式系数。在`main`函数中调用这两个函数,并输出结果。
阅读全文