Permalink
Browse files

Array.avg Array.stdDev

  • Loading branch information...
1 parent c04ee7b commit a2b62096929a59808b0300142bb1beaa246120d8 @erh erh committed Nov 10, 2009
Showing with 25 additions and 0 deletions.
  1. +8 −0 jstests/array3.js
  2. +17 −0 shell/utils.js
View
@@ -0,0 +1,8 @@
+
+assert.eq( 5 , Array.sum( [ 1 , 4 ] ), "A" )
+assert.eq( 2.5 , Array.avg( [ 1 , 4 ] ), "B" )
+
+arr = [ 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 ]
+assert.eq( 5 , Array.avg( arr ) , "C" )
+assert.eq( 2 , Array.stdDev( arr ) , "D" )
+
View
@@ -255,6 +255,23 @@ Array.sum = function( arr ){
return s;
}
+Array.avg = function( arr ){
+ if ( arr.length == 0 )
+ return null;
+ return Array.sum( arr ) / arr.length;
+}
+
+Array.stdDev = function( arr ){
+ var avg = Array.avg( arr );
+ var sum = 0;
+
+ for ( var i=0; i<arr.length; i++ ){
+ sum += Math.pow( arr[i] - avg , 2 );
+ }
+
+ return Math.sqrt( sum / arr.length );
+}
+
if ( ! ObjectId.prototype )
ObjectId.prototype = {}

0 comments on commit a2b6209

Please sign in to comment.