均值 与 方差 的数值计算方法。
在阅读 px4 代码时遇到了求取均值与方差的代码实现,比较优美:
https://github.com/PX4/ecl/blob/master/validation/data_validator.cpp#L88-L114
for (unsigned i = 0; i < dimensions; i++) {
if (_time_last == 0) {
_mean[i] = 0;
_lp[i] = val[i];
_M2[i] = 0;
} else {
float lp_val = val[i] - _lp[i];
float delta_val = lp_val - _mean[i];
_mean[i] += delta_val / _event_count;
_M2[i] += delta_val * (lp_val - _mean[i]);
_rms[i] = sqrtf(_M2[i] / (_event_count - 1));
if (fabsf(_value[i] - val[i]) < 0.000001f) {
_value_equal_count++;
} else {
_value_equal_count = 0;
}
}
_vibe[i] = _vibe[i] * 0.99f + 0.01f * fabsf(val[i] - _lp[i]);
// XXX replace with better filter, make it auto-tune to update rate
_lp[i] = _lp[i] * 0.99f + 0.01f * val[i];
_value[i] = val[i];
}
对其分析如下:
以下公式中,约定
平均值
即:
//此处代码为 PX4 validator 代码:
float delta_val = lp_val - _mean[i];
_mean[i] += delta_val / _event_count;
样本方差
方差在统计中,分母为
//此处代码为 PX4 validator 代码:
_M2[i] += delta_val * (lp_val - _mean[i]);
_rms[i] = sqrtf(_M2[i] / (_event_count - 1));
此处,_M2[i] 的计算公式如下:
时间仓促,此公式未查到出处,怀疑与下一行分母的