用C语言编写一个最小二乘法代码
时间: 2024-05-21 07:12:24 浏览: 74
好的,您可以参考以下代码实现最小二乘法:
#include <stdio.h>
#define N 5 // 样本数量
#define M 2 // 参数个数
// 计算矩阵乘法
void matrix_multiply(double a[N][M], double b[M][N], double c[N][N]) {
int i, j, k;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
c[i][j] = 0;
for (k = 0; k < M; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main() {
// 样本数据
double x[N][M] = {{1, 3}, {2, 5}, {3, 7}, {4, 9}, {5, 11}};
double y[N] = {5, 7, 9, 11, 13};
// 计算A的转置矩阵
double a_t[M][N];
int i, j;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
a_t[i][j] = x[j][i];
}
}
// 计算A的转置矩阵乘以A
double a_t_a[M][M];
matrix_multiply(a_t, x, a_t_a);
// 计算A的转置矩阵乘以b
double a_t_y[M];
for (i = 0; i < M; i++) {
a_t_y[i] = 0;
for (j = 0; j < N; j++) {
a_t_y[i] += a_t[i][j] * y[j];
}
}
// 解线性方程组
double a[M][M + 1];
for (i = 0; i < M; i++) {
for (j = 0; j < M; j++) {
a[i][j] = a_t_a[i][j];
}
a[i][M] = a_t_y[i];
}
for (i = 0; i < M; i++) {
for (j = i + 1; j < M; j++) {
double f = a[j][i] / a[i][i];
for (int k = i; k <= M; k++) {
a[j][k] -= a[i][k] * f;
}
}
}
double res[M];
for (i = M - 1; i >= 0; i--) {
res[i] = a[i][M] / a[i][i];
for (j = i - 1; j >= 0; j--) {
a[j][M] -= a[j][i] * res[i];
}
}
// 输出结果
printf("参数值:\n");
for (i = 0; i < M; i++) {
printf(" x%d = %f\n", i, res[i]);
}
return 0;
}
阅读全文