C语言最小二乘法怎么写
时间: 2023-10-24 21:05:31 浏览: 77
这是一个使用C语言实现最小二乘法的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_POINTS 100
double x[MAX_POINTS];
double y[MAX_POINTS];
double sum(double *data, int n) {
double s = 0.0;
for (int i = 0; i < n; i++) {
s += data[i];
}
return s;
}
double mean(double *data, int n) {
return sum(data, n) / n;
}
double covariance(double *x, double *y, int n) {
double mx = mean(x, n);
double my = mean(y, n);
double s = 0.0;
for (int i = 0; i < n; i++) {
s += (x[i] - mx) * (y[i] - my);
}
return s;
}
double variance(double *data, int n) {
double m = mean(data, n);
double s = 0.0;
for (int i = 0; i < n; i++) {
s += (data[i] - m) * (data[i] - m);
}
return s;
}
double slope(double *x, double *y, int n) {
return covariance(x, y, n) / variance(x, n);
}
double intercept(double *x, double *y, int n) {
double m = mean(y, n) - slope(x, y, n) * mean(x, n);
return m;
}
void print_points(double *x, double *y, int n) {
for (int i = 0; i < n; i++) {
printf("(%lf, %lf)\n", x[i], y[i]);
}
}
int main() {
int n;
printf("Enter number of points (max %d): ", MAX_POINTS);
scanf("%d", &n);
if (n <= 0 || n > MAX_POINTS) {
printf("Invalid number of points.\n");
return 1;
}
for (int i = 0; i < n; i++) {
printf("Enter point %d (x y): ", i + 1);
scanf("%lf %lf", &x[i], &y[i]);
}
double m = slope(x, y, n);
double b = intercept(x, y, n);
printf("Linear equation: y = %lfx + %lf\n", m, b);
return 0;
}
```
该程序首先提示用户输入点的数量,然后依次提示用户输入每个点的坐标。接下来,它计算最小二乘线的斜率和截距,并输出线性方程。
阅读全文