#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// 定义线性回归模型的结构体
typedef struct {
double slope; // 斜率
double intercept; // 截距
} LinearRegressionModel;
// 训练线性回归模型
void trainLinearRegression(double *X, double *y, int n, LinearRegressionModel *model) {
double sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0;
for (int i = 0; i < n; i++) {
sumX += X[i];
sumY += y[i];
sumXY += X[i] * y[i];
sumX2 += X[i] * X[i];
}
model->slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
model->intercept = (sumY - model->slope * sumX) / n;
}
// 使用线性回归模型进行预测
double predict(LinearRegressionModel model, double currentOutput) {
return model.slope * currentOutput + model.intercept;
}
int main() {
double X[] = {100, 200, 300, 400}; // 光照强度数据
double y[] = {50, 100, 150, 200}; // 光敏元件输出数值数据
int n = 4;
LinearRegressionModel model;
trainLinearRegression(X, y, n, &model);
double currentOutput = 250; // 当前光敏元件输出数值
double predictedValue = predict(model, currentOutput);
printf("补偿值为: %f\n", predictedValue);
return 0;
}
|