加权多项式拟合C++代码实现
时间: 2024-01-03 17:05:12 浏览: 96
基于C++实现多项式拟合和单位自动转换提供温度的数据拟合(源码+数据).rar
以下是加权多项式拟合的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;
}
```
阅读全文