最小二乘法拟合直线
#define N 4
/*
* 最小二乘法拟合直线 y = k0 + k1 * x
* x[] 拟合数据的x向量
* y[] 拟合数据的y向量
* k[] 拟合后的系数向量 k0 = k[0], k1 = k[1]
* */
void fitLineMethod(double x[N], double y[N], double k[2]) {
double k1 = 0, k2 = 0, k3 = 0, k4 = 0, k5 = 0;
k[0] = 0;
k[1] = 0;
for (int i = 0; i < N; i++) {
k1 += x[i] * x[i];
k2 += x[i];
k3 += x[i] * y[i];
k4 += 1;
k5 += y[i];
}
if (k2 * k2 != k1 * k4) {
k[0] = (k2 * k3 - k1 * k5) / (k2 * k2 - k1 * k4);
k[1] = (k2 * k5 - k3 * k4) / (k2 * k2 - k1 * k4);
}
}