qt生成n个点绘制二次函数曲线并计算出函数曲线 a b c 的值并计算出拟合值R2
时间: 2023-12-23 17:03:26 浏览: 151
对平面多个点进行曲线拟合
以下是一个简单的用Qt绘制二次函数曲线的示例代码,并计算出函数曲线a、b、c的值和拟合值R2:
```cpp
#include <QtWidgets>
class QuadraticFunctionWidget : public QWidget
{
public:
QuadraticFunctionWidget(QWidget *parent = nullptr) : QWidget(parent)
{
setWindowTitle("Quadratic Function");
// 设置绘图区域大小
setFixedSize(500, 500);
// 生成n个点
const int n = 20;
for (int i = 0; i < n; ++i) {
double x = i * 1.0 / (n - 1);
double y = a * x * x + b * x + c;
m_points.append(QPointF(x, y));
}
// 计算函数曲线的a、b、c值
double x_sum = 0, x2_sum = 0, x3_sum = 0, x4_sum = 0;
double y_sum = 0, xy_sum = 0, x2y_sum = 0;
for (int i = 0; i < n; ++i) {
double x = m_points[i].x();
double y = m_points[i].y();
x_sum += x;
x2_sum += x * x;
x3_sum += x * x * x;
x4_sum += x * x * x * x;
y_sum += y;
xy_sum += x * y;
x2y_sum += x * x * y;
}
double denominator = n * x2_sum * x4_sum - x3_sum * x3_sum - x2_sum * x2_sum * n
+ 2 * x2_sum * x3_sum + x_sum * x_sum * x4_sum
- n * x_sum * x2_sum * x2_sum;
a = (n * x2y_sum - x2_sum * y_sum - x_sum * xy_sum + n * x_sum * x2_sum * b) / denominator;
b = (xy_sum - x_sum * y_sum - a * (x2_sum - n * x_sum * x_sum)) / x2_sum;
c = (y_sum - a * x2_sum - b * x_sum) / n;
// 计算R2值
double y_mean = y_sum / n;
double ss_tot = 0, ss_res = 0;
for (int i = 0; i < n; ++i) {
double y = m_points[i].y();
ss_tot += (y - y_mean) * (y - y_mean);
ss_res += (y - (a * m_points[i].x() * m_points[i].x() + b * m_points[i].x() + c))
* (y - (a * m_points[i].x() * m_points[i].x() + b * m_points[i].x() + c));
}
R2 = 1 - ss_res / ss_tot;
}
protected:
void paintEvent(QPaintEvent *event) override
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// 绘制坐标系
painter.translate(width() / 2, height() / 2);
painter.drawLine(QPointF(-width() / 2, 0), QPointF(width() / 2, 0));
painter.drawLine(QPointF(0, -height() / 2), QPointF(0, height() / 2));
// 绘制函数曲线
painter.setPen(QPen(Qt::red, 2));
QPainterPath path;
for (int i = 0; i < m_points.size(); ++i) {
QPointF p = m_points[i] * QPointF(width() / 2, -height() / 2);
if (i == 0) {
path.moveTo(p);
} else {
path.lineTo(p);
}
}
painter.drawPath(path);
}
private:
QVector<QPointF> m_points;
double a = 1, b = 2, c = 1; // 二次函数曲线的a、b、c值
double R2 = 0; // 拟合值R2
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QuadraticFunctionWidget widget;
widget.show();
return app.exec();
}
```
在上面的代码中,我们生成了n个均匀分布的点,并使用这些点拟合出一个二次函数曲线。然后,我们计算出函数曲线的a、b、c值和拟合值R2,并在窗口中绘制出这个二次函数曲线。
阅读全文