三元最小二乘C语言代码
时间: 2023-07-10 13:09:15 浏览: 143
以下是三元最小二乘 C 语言代码示例:
```c
#include <stdio.h>
#include <math.h>
// 三元最小二乘函数
void three_ls(double x[], double y[], double z[], int n, double *a, double *b, double *c)
{
double sx = 0.0, sy = 0.0, sz = 0.0;
double sxx = 0.0, sxy = 0.0, sxz = 0.0, syy = 0.0, syz = 0.0, szz = 0.0;
for (int i = 0; i < n; i++) {
sx += x[i];
sy += y[i];
sz += z[i];
sxx += x[i] * x[i];
sxy += x[i] * y[i];
sxz += x[i] * z[i];
syy += y[i] * y[i];
syz += y[i] * z[i];
szz += z[i] * z[i];
}
double det_x = (syy * szz) - (syz * syz);
double det_y = (sxx * szz) - (sxz * sxz);
double det_z = (sxx * syy) - (sxy * sxy);
double det = (sx * ((syy * szz) - (syz * syz))) - (sy * ((sxy * szz) - (sxz * syz))) + (sz * ((sxy * syz) - (syy * sxz)));
*a = det_x ? (((sy * ((sxz * szz) - (sxy * syz))) - (sz * ((sxx * szz) - (sxz * sxz))) + (det * (sxy - sxz))) / det_x) : 0.0;
*b = det_y ? (((sx * ((syz * szz) - (syy * syz))) - (sz * ((sxx * syz) - (sxz * sxy))) + (det * (syz - sxy))) / det_y) : 0.0;
*c = det_z ? (((sx * ((syy * szz) - (syz * syz))) - (sy * ((sxy * szz) - (sxz * syz))) + (det * (sxy - syz))) / det_z) : 0.0;
}
int main()
{
double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
double y[] = {3.0, 5.0, 7.0, 9.0, 11.0};
double z[] = {2.0, 4.0, 6.0, 8.0, 10.0};
int n = 5;
double a, b, c;
three_ls(x, y, z, n, &a, &b, &c);
printf("a = %lf\n", a);
printf("b = %lf\n", b);
printf("c = %lf\n", c);
return 0;
}
```
这段代码实现了三元最小二乘,使用了三个数组 x、y、z 存储数据,n 表示数据个数,a、b、c 分别表示拟合直线的三个系数。
阅读全文