stats.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * Define some useful statistical functions on arrays of numbers
  3. */
  4. Array.prototype.sum = function() {
  5. var i, sum = 0;
  6. for (i = 0; i < this.length; i++) {
  7. sum += this[i];
  8. }
  9. return sum;
  10. }
  11. Array.prototype.max = function() {
  12. return Math.max.apply(null, this);
  13. }
  14. Array.prototype.min = function() {
  15. return Math.min.apply(null, this);
  16. }
  17. Array.prototype.mean = function() {
  18. return this.sum() / this.length;
  19. }
  20. Array.prototype.average = Array.prototype.mean;
  21. Array.prototype.median = function() {
  22. var sorted = this.sort( function(a,b) { return a-b; }),
  23. len = sorted.length;
  24. if (len % 2) {
  25. return sorted[Math.floor(len / 2)]; // Odd
  26. } else {
  27. return (sorted[len/2 - 1] + sorted[len/2]) / 2; // Even
  28. }
  29. }
  30. Array.prototype.stdDev = function(sample) {
  31. var i, sumSqr = 0, mean = this.mean(), N;
  32. if (sample) {
  33. // Population correction if this is a sample
  34. N = this.length - 1;
  35. } else {
  36. // Standard deviation of just the array
  37. N = this.length;
  38. }
  39. for (i = 0; i < this.length; i++) {
  40. sumSqr += Math.pow(this[i] - mean, 2);
  41. }
  42. return Math.sqrt(sumSqr / N);
  43. }