Polynomial 回归 C++ 代码
时间: 2024-05-01 12:22:59 浏览: 104
C 代码 计算伯恩斯坦多项式.rar
以下是一个简单的多项式回归的 C++ 代码示例:
```c++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// 计算多项式回归系数
vector<double> polyfit(vector<double> x, vector<double> y, int degree)
{
int n = x.size();
vector<double> coeffs(degree + 1, 0);
vector<double> sx(2 * degree + 1, 0);
vector<double> sy(degree + 1, 0);
for (int i = 0; i < n; ++i)
{
double xi = x[i], yi = y[i];
for (int j = 0; j <= degree; ++j)
{
sx[j] += pow(xi, j);
}
for (int j = 0; j <= degree; ++j)
{
sy[j] += yi * pow(xi, j);
}
}
for (int i = 0; i <= degree; ++i)
{
for (int j = 0; j <= degree; ++j)
{
coeffs[i] += pow(-1, i + j) * sy[j] * sx[i + j];
}
coeffs[i] /= pow(x.size(), 2 * degree - i);
}
return coeffs;
}
int main()
{
vector<double> x = { 1, 2, 3, 4, 5 };
vector<double> y = { 1.2, 3.5, 4.2, 4.8, 5.1 };
int degree = 2;
vector<double> coeffs = polyfit(x, y, degree);
cout << "The coefficients are: ";
for (int i = 0; i <= degree; ++i)
{
cout << coeffs[i] << " ";
}
cout << endl;
return 0;
}
```
这个程序使用向量表示多项式回归的输入数据。在 `polyfit` 函数中,我们首先分配了一些向量来存储计算所需的中间结果。然后,我们使用两个循环来计算 $s_{x,j}$ 和 $s_{y,j}$。最后,我们使用第三个循环计算回归系数。
阅读全文