Created
November 13, 2012 08:51
-
-
Save qubyte/4064710 to your computer and use it in GitHub Desktop.
Calculate a running standard deviation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A standard deviation object constructor. Running deviation (avoid growing arrays) which | |
// is round-off error resistant. Based on an algorithm found in a Knuth book. | |
function StandardDeviation(firstMeasurement) { | |
this.workData = firstMeasurement; | |
this.lastWorkData = null; | |
this.S = 0; | |
this.count = 1; | |
} | |
// Add a measurement. Also calculates updates to stepwise parameters which are later used | |
// to determine sigma. | |
StandardDeviation.prototype.addMeasurement = function (measurement) { | |
this.count += 1; | |
this.lastWorkData = this.workData; | |
this.workData = this.workData + (measurement - this.workData) / this.count; | |
this.S = this.S + (measurement - this.lastWorkData) * (measurement - this.workData); | |
}; | |
// Performs the final step needed to get the standard deviation and returns it. | |
StandardDeviation.prototype.get = function () { | |
return Math.sqrt(this.S / (this.count - 1)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Below is typescript version, it's more convenient to have a class with empty constructor since it imposes less constraints on when this class can be initialized (before you have your first value or after):