加权三次多项式拟合C++代码实现
时间: 2024-01-03 15:05:12 浏览: 187
以下是加权三次多项式拟合的C++代码实现,其中使用了Eigen库进行矩阵计算:
```cpp
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
// 输入数据
int n = 5; // 数据点个数
MatrixXd X(n, 4);
VectorXd y(n);
VectorXd w(n);
X << 1, 1, 1, 1,
2, 4, 8, 16,
3, 9, 27, 81,
4, 16, 64, 256,
5, 25, 125, 625;
y << 1, 2, 3, 4, 5;
w << 1, 2, 3, 4, 5;
// 计算加权三次多项式系数
MatrixXd A(n, 4);
A << w.array().sqrt().matrix().asDiagonal() * X;
VectorXd b = w.array().sqrt() * y;
Vector4d coef = A.colPivHouseholderQr().solve(b);
// 输出结果
std::cout << "Coefficients: " << coef.transpose() << std::endl;
return 0;
}
```
相关问题
加权多项式拟合C++代码实现
以下是加权多项式拟合的C++代码实现,包括数据读取、计算多项式系数和输出结果三个部分:
1.数据读取部分:
```c++
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// 读取数据文件
void readData(string filename, vector<double>& x, vector<double>& y, vector<double>& w) {
ifstream fin(filename);
double xi, yi, wi;
while (fin >> xi >> yi >> wi) {
x.push_back(xi);
y.push_back(yi);
w.push_back(wi);
}
fin.close();}
```
2.计算多项式系数部分:
```c++
#include <Eigen/Dense>
#include <vector>
using namespace Eigen;
using namespace std;
// 计算多项式系数
VectorXd polyfit(vector<double>& x, vector<double>& y, vector<double>& w, int order) {
int n = x.size();
MatrixXd A(n, order + 1);
VectorXd b(n);
VectorXd wv(n);
for (int i = 0; i < n; i++) {
wv(i) = sqrt(w[i]);
for (int j = 0; j <= order; j++) {
A(i, j) = pow(x[i], j) * wv(i);
}
b(i) = y[i] * wv(i);
}
VectorXd coeffs = A.colPivHouseholderQr().solve(b);
return coeffs;
}
```
3.输出结果部分:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 输出结果
void printResult(VectorXd coeffs) {
int n = coeffs.size() - 1;
cout << "The polynomial is: ";
for (int i = n; i >= 0; i--) {
cout << coeffs(n - i) << "x^" << i;
if (i > 0) {
cout << " + ";
}
}
cout << endl;
}
```
完整代码如下:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;
// 读取数据文件
void readData(string filename, vector<double>& x, vector<double>& y, vector<double>& w) {
ifstream fin(filename);
double xi, yi, wi;
while (fin >> xi >> yi >> wi) {
x.push_back(xi);
y.push_back(yi);
w.push_back(wi);
}
fin.close();
}
// 计算多项式系数
VectorXd polyfit(vector<double>& x, vector<double>& y, vector<double>& w, int order) {
int n = x.size();
MatrixXd A(n, order + 1);
VectorXd b(n);
VectorXd wv(n);
for (int i = 0; i < n; i++) {
wv(i) = sqrt(w[i]);
for (int j = 0; j <= order; j++) {
A(i, j) = pow(x[i], j) * wv(i);
}
b(i) = y[i] * wv(i);
}
VectorXd coeffs = A.colPivHouseholderQr().solve(b);
return coeffs;
}
// 输出结果
void printResult(VectorXd coeffs) {
int n = coeffs.size() - 1;
cout << "The polynomial is: ";
for (int i = n; i >= 0; i--) {
cout << coeffs(n - i) << "x^" << i;
if (i > 0) {
cout << " + ";
}
}
cout << endl;
}
int main() {
vector<double> x, y, w;
readData("data.txt", x, y, w);
VectorXd coeffs = polyfit(x, y, w, 2);
printResult(coeffs);
return 0;
}
```
阅读全文