3元最小二乘拟合C语言代码 格式:z=ax+by+c
时间: 2023-12-12 21:04:05 浏览: 102
用函数:y=ax+b来拟合数据
以下是使用3元最小二乘法拟合的C语言代码,格式为z = ax + by + c:
```c
#include <stdio.h>
void least_square_fit(double x[], double y[], double z[], int n, double *a, double *b, double *c) {
double sum_x = 0.0, sum_y = 0.0, sum_z = 0.0; // 存储x、y、z的和
double sum_xx = 0.0, sum_xy = 0.0, sum_xz = 0.0; // 存储x^2、xy、xz的和
double sum_yy = 0.0, sum_yz = 0.0; // 存储y^2、yz的和
// 计算各个和的值
for (int i = 0; i < n; ++i) {
sum_x += x[i];
sum_y += y[i];
sum_z += z[i];
sum_xx += x[i] * x[i];
sum_xy += x[i] * y[i];
sum_xz += x[i] * z[i];
sum_yy += y[i] * y[i];
sum_yz += y[i] * z[i];
}
// 求解3元方程组
double det = sum_xx * sum_yy * n + 2 * sum_x * sum_y * sum_xy - sum_x * sum_x * sum_yy - sum_y * sum_y * sum_xx - n * sum_xy * sum_xy;
double det_a = sum_xz * sum_yy * n + sum_x * sum_y * sum_yz + sum_z * sum_xy * n - sum_x * sum_yz * sum_y - sum_z * sum_xx * n;
double det_b = sum_xx * sum_yz * n + sum_xz * sum_y * n + sum_x * sum_y * sum_z - sum_x * sum_yz * sum_x - sum_xy * sum_z * n;
double det_c = sum_xx * sum_yy * sum_z + sum_x * sum_y * sum_yz + sum_xy * sum_xz * n - sum_xz * sum_yy * sum_x - sum_xy * sum_xy * sum_z - sum_xx * sum_yz * sum_y;
// 计算a、b、c
*a = det_a / det;
*b = det_b / det;
*c = det_c / det;
}
int main() {
double x[] = {1.0, 2.0, 3.0, 4.0, 5.0}; // x的数据
double y[] = {2.0, 3.0, 4.0, 5.0, 6.0}; // y的数据
double z[] = {3.0, 4.0, 5.0, 6.0, 7.0}; // z的数据
int n = 5; // 数据长度
double a, b, c; // 存储拟合结果
least_square_fit(x, y, z, n, &a, &b, &c);
printf("z = %.2fx + %.2fy + %.2f\n", a, b, c);
return 0;
}
```
请注意,此代码仅适用于数据点的数量为3或更多的情况。如果只有两个数据点,则无法使用3元最小二乘法进行拟合。
阅读全文