已知x,y,z数组,求解最小二乘拟合C语言代码 格式:z=Qz*x-t*y+k
时间: 2024-02-05 13:12:47 浏览: 155
以下是使用最小二乘法拟合的 C 代码,假设 x、y、z 都是长度为 n 的数组:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void least_squares_fit(double *x, double *y, double *z, int n, double *Qz, double *t, double *k) {
double sum_x = 0.0, sum_y = 0.0, sum_z = 0.0;
double sum_xx = 0.0, sum_xy = 0.0, sum_xz = 0.0, sum_yy = 0.0, sum_yz = 0.0;
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];
}
double det = (n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y) - (n * sum_xy - sum_x * sum_y) * (n * sum_xy - sum_x * sum_y);
*Qz = ((n * sum_xx - sum_x * sum_x) * sum_yz - (n * sum_xy - sum_x * sum_y) * sum_xz) / det;
*t = ((n * sum_yy - sum_y * sum_y) * sum_xz - (n * sum_xy - sum_x * sum_y) * sum_yz) / det;
*k = (sum_z - *Qz * sum_xx - *t * sum_yy) / n;
}
int main() {
int n = 10;
double x[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
double y[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
double z[] = {3.0, 5.0, 7.0, 9.0, 11.0, 13.0, 15.0, 17.0, 19.0, 21.0};
double Qz, t, k;
least_squares_fit(x, y, z, n, &Qz, &t, &k);
printf("z = %.2f * x - %.2f * y + %.2f\n", Qz, t, k);
return 0;
}
```
注:该代码仅为示例,实际使用时需要根据具体问题进行调整和优化。
阅读全文