qt生成八个点绘制二次函数曲线并计算出函数曲线y = a * x^2 + b * x + c并计算出拟合值R2
时间: 2024-01-21 19:18:13 浏览: 91
以下是一个使用 Qt 绘制二次函数曲线并计算拟合值 R2 的示例程序:
```
#include <QtWidgets>
class QuadraticFunctionWidget : public QWidget
{
public:
QuadraticFunctionWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
setWindowTitle(tr("Quadratic Function"));
// 设置初始参数
a = 1.0;
b = 0.0;
c = 0.0;
// 创建绘图窗口
chartView = new QChartView(this);
chartView->setRenderHint(QPainter::Antialiasing);
// 创建数据序列
series = new QScatterSeries();
for (int i = 0; i < 8; i++) {
QPointF point(i, 0.0); // x 坐标从 0 到 7
series->append(point);
}
// 添加数据序列到图表
chart = new QChart();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setAnimationOptions(QChart::SeriesAnimations);
// 显示图表
chartView->setChart(chart);
chartView->setMinimumSize(640, 480);
// 创建参数输入框和计算按钮
aLineEdit = new QLineEdit(QString::number(a));
bLineEdit = new QLineEdit(QString::number(b));
cLineEdit = new QLineEdit(QString::number(c));
calculateButton = new QPushButton(tr("Calculate"));
// 连接计算按钮的槽函数
connect(calculateButton, &QPushButton::clicked, this, &QuadraticFunctionWidget::calculate);
// 创建布局
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(chartView);
layout->addWidget(new QLabel(tr("y = ax^2 + bx + c")));
QHBoxLayout *paramLayout = new QHBoxLayout();
paramLayout->addWidget(new QLabel(tr("a:")));
paramLayout->addWidget(aLineEdit);
paramLayout->addWidget(new QLabel(tr("b:")));
paramLayout->addWidget(bLineEdit);
paramLayout->addWidget(new QLabel(tr("c:")));
paramLayout->addWidget(cLineEdit);
paramLayout->addWidget(calculateButton);
layout->addLayout(paramLayout);
setLayout(layout);
}
private:
QChartView *chartView;
QChart *chart;
QScatterSeries *series;
QLineEdit *aLineEdit;
QLineEdit *bLineEdit;
QLineEdit *cLineEdit;
QPushButton *calculateButton;
double a;
double b;
double c;
void calculate()
{
// 读取参数
a = aLineEdit->text().toDouble();
b = bLineEdit->text().toDouble();
c = cLineEdit->text().toDouble();
// 计算函数曲线
QVector<QPointF> points;
for (int i = 0; i < 8; i++) {
double x = i;
double y = a * x * x + b * x + c;
points.append(QPointF(x, y));
}
// 更新数据序列
series->replace(points);
// 计算拟合值 R2
double sumX = 0.0;
double sumY = 0.0;
double sumXY = 0.0;
double sumX2 = 0.0;
double sumY2 = 0.0;
int n = points.size();
for (int i = 0; i < n; i++) {
double x = points[i].x();
double y = points[i].y();
sumX += x;
sumY += y;
sumXY += x * y;
sumX2 += x * x;
sumY2 += y * y;
}
double meanX = sumX / n;
double meanY = sumY / n;
double SSE = sumY2 - (sumY * sumY) / n;
double SSR = (sumXY - sumX * sumY / n) * (sumXY - sumX * sumY / n) / (sumX2 - sumX * sumX / n);
double SST = SSE + SSR;
double R2 = SSR / SST;
// 显示拟合值 R2
QMessageBox::information(this, tr("R2"), tr("R2 = %1").arg(R2));
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QuadraticFunctionWidget widget;
widget.show();
return app.exec();
}
```
该程序创建了一个窗口,包含一个图表和三个参数输入框和一个计算按钮。用户可以输入二次函数的三个参数,并点击计算按钮来绘制函数曲线和计算拟合值 R2。在计算拟合值 R2 时,程序使用了最小二乘法的公式来计算。
阅读全文