Created
September 3, 2011 17:34
-
-
Save trevorc/1191502 to your computer and use it in GitHub Desktop.
Compute the first four sample moments about the mean (and the standard deviation) iteratively from a stream of samples
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
BEGIN { OFS = "\t" } | |
{ | |
accs[0] += 1 | |
accs[1] += $1 | |
accs[2] += (val2 = $1 * $1) | |
accs[3] += (val3 = val2 * $1) | |
accs[4] += (val4 = val3 * $1) | |
mean = accs[1] / accs[0] | |
mean2 = mean * mean | |
mean3 = mean2 * mean | |
var = (accs[2] - accs[1] * mean) / accs[0] | |
std = sqrt(var) | |
if (var > 0) { | |
skew = ( accs[3] \ | |
- 3 * accs[2] * mean \ | |
+ 2 * accs[1] * mean2 \ | |
) / (var * std * accs[0]) | |
kurt = ( accs[4] \ | |
- 4 * accs[3] * mean \ | |
+ 6 * accs[2] * mean2 \ | |
- 3 * accs[1] * mean3 \ | |
) / (var * var * accs[0]) | |
} else { | |
skew = kurt = "" | |
} | |
print $1, mean, std, var, skew, kurt | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment