qt c++拟合直线
时间: 2024-06-04 11:04:58 浏览: 178
在Qt C++中拟合直线可以使用最小二乘法,以下是一个简单的拟合直线的示例代码:
```
#include <QCoreApplication>
#include <QtMath>
#include <QDebug>
double fitLine(const QVector<double>& xData, const QVector<double>& yData, double& slope, double& yIntercept)
{
double xSum = 0, ySum = 0, xySum = 0, xSquaredSum = 0;
int n = xData.size();
for(int i=0; i<n; i++)
{
xSum += xData[i];
ySum += yData[i];
xySum += xData[i] * yData[i];
xSquaredSum += xData[i] * xData[i];
}
double denominator = n * xSquaredSum - qPow(xSum, 2);
if(denominator == 0)
return 0;
slope = (n * xySum - xSum * ySum) / denominator;
yIntercept = (ySum * xSquaredSum - xSum * xySum) / denominator;
// calculate r-squared
double yMean = ySum / n;
double ssTotal = 0, ssResidual = 0;
for(int i=0; i<n; i++)
{
ssTotal += qPow(yData[i] - yMean, 2);
ssResidual += qPow(yData[i] - yIntercept, 2);
}
return 1 - (ssResidual / ssTotal);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVector<double> xData{1, 2, 3, 4, 5};
QVector<double> yData{2.1, 3.9, 6.1, 8.2, 9.8};
double slope = 0, yIntercept = 0;
double rSquared = fitLine(xData, yData, slope, yIntercept);
qDebug() << "Slope:" << slope << ", Y Intercept:" << yIntercept << ", R-Squared:" << rSquared;
return a.exec();
}
```
其中`xData`和`yData`分别是x和y轴数据点的向量,`slope`和`yIntercept`是拟合出的直线的斜率和截距。`fitLine`函数返回的是R平方值,用于衡量模型的拟合程度。
阅读全文