简介
struct DataPoint {
double x;
double y;
};
std::vector<DataPoint> dataPoints;
void leastSquares(const std::vector<DataPoint>& dataPoints, double& slope, double& intercept) {
// 计算斜率和截距
// ...
}
std::cout << "拟合直线的方程为: y = " << slope << "x + " << intercept << std::endl;
假设我们有一组散点数据:
P1(1, 3)
P2(2, 5)
P3(3, 7)
P4(4, 9)
P5(5, 11)
P6(6,13 )
P7(7, 15)
P8(8, 17)
P9(9, 19)
#include <IOStream>
#include <vector>
#include <numeric>
using Parameter = struct {
double k; // 斜率
double b; // 截距
};
// 最小二乘法计算过程
bool LeastSquares(std::vector<double>& X, std::vector<double>& Y, Parameter& param)
{
if (X.empty() || Y.empty())
return false;
int n = X.size();
double sumX = std::accumulate(X.begin(), X.end(), 0.0);
double sumY = std::accumulate(Y.begin(), Y.end(), 0.0);
double sumXY = 0.0;
double sumX2 = 0.0;
for (int i = 0; i < n; i++) {
sumXY += X[i] * Y[i];
sumX2 += X[i] * X[i];
}
double meanX = sumX / n;
double meanY = sumY / n;
param.k = (sumXY - n * meanX * meanY) / (sumX2 - n * meanX * meanX);
param.b = meanY - param.k * meanX;
return true;
}
int mAIn()
{
std::vector<double> X = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<double> Y = {3, 5, 7, 9, 11, 13, 15, 17, 19};
Parameter param;
if (LeastSquares(X, Y, param)) {
std::cout << "拟合直线的方程为: y = " << param.k << "x + " << param.b << std::endl;
} else {
std::cout << "拟合失败" << std::endl;
}
return 0;
}