Skip to content

Instantly share code, notes, and snippets.

@icholy
Created November 11, 2015 18:16
Show Gist options
  • Select an option

  • Save icholy/9586784a82be7346a39e to your computer and use it in GitHub Desktop.

Select an option

Save icholy/9586784a82be7346a39e to your computer and use it in GitHub Desktop.
  • The gain is how much of the new measurement to use.
  • The measurement error is constant and depends on the source.
interface Estimate {
  value: number;
  error: number;
}

class KalmanFilter {

  constructor(
    private estimate: Estimate,
    private measurementError: number
  ) {}

  iterate(measurement: number): number {
    var prev = this.estimate;
    var gain = prev.error / (prev.error + measurementError);
    this.estimate = {
      value: prev.value + (gain * (measurement - prev.value)),
      error: (1 - gain) * prev.error
    };
    return this.estimate.value;
  }
}

var trueValue = 72;
var measurementError = 4;

function getMeasurement(): number {
  var noise = (Math.random() * 9) - 4;
  return trueValue + noise;
}

var initial: Estimate = {
  value: 68,
  error: 2
};

var i;
var kalman = new KalmanFilter(initial, measurementError);

for (i = 0; i < 1000; i++) {
  var m = getMeasurement();
  var e = kalman.iterate(m);
  console.log("m:", m, "e:", e, "v:", trueValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment