I am using the following smoothing function to smooth speed readings from GPS.
void smoothing_init()
{
k = 0;
kalman_init(0.0625, 32, 1.3833094, 0);
}
void kalman_init(double _q, double _r, double _p, double intial_value)
{
q = _q;
r = _r;
p = _p;
x = intial_value;
}
double smoothing_add_sample(double measurement)
{
p = p + q;
k = p / (p + r);
x = x + k * (measurement - x);
p = (1 - k) * p;
return x;
}
However, sometimes this gives me smoothing values 700(the normal range is 0-150) and then going down. I guess it happens when I initialize routine with 0 but immediately receiving reading above 0 (for example 40, 50).
How can I tweak those functions to naturally prevent such spikes, but still be able to smooth data.
The Kalman filter is an estimator, which minimizes the variance (
pin your code) of a system state (x) of a linear system. The variancepcan be interpreted as a measure of confidence in the value ofx.For each time step
kthe filter performs two steps:x[k+1] = x[k] + w[k]wherew[k]is zero-mean Gaussian noise with varianceq). It means here that the state variance is increased byq.measurement[k] = x[k] + v[k]wherev[k]is zero-mean Gaussian noise with variancer).For classic estimation problems
pis initialized with a very large value (little confidence in the initial valuex). Over timepdecreases to a value somewhere aroundq. Note thepis independent of themeasurement, so it only depends onq,randp[0].So for the tweaking:
p, i.e.p/r>>0; the initialization value ofxdoes not really matter.r/qadjusts how strong the smoothing is (r/q=0then there’s no smoothing at all).r,q, you can assume Gaussian noise: Then you have a 95% probability the true value lies in the confidence interval of[x-2*sqrt(p), x+2*sqrt(p)].