On Jun 21, 2006, at 4:32 PM, Beau Hartshorne wrote:

>
> I needed median and mean functions for something I'm working on.
> Should they go into MochiKit somewhere? Are they correct? Fast enough?
>
> /* http://www.nist.gov/dads/HTML/mean.html */
> var mean = function() {
>      var data = flattenArguments(arguments);
>      return sum(data) / data.length;
> };
>
> /* http://www.nist.gov/dads/HTML/median.html */
> var median = function() {
>      var data = flattenArguments(arguments);
>      data.sort(compare);
>      if (data.length % 2 == 0) {
>          var upper = data.length / 2;
>          return (data[upper] + data[upper - 1]) / 2;
>      } else {
>          return data[(data.length - 1) / 2];
>      }
> };

These look correct and fast enough. I might've written mean such that  
it inlined more or less what flattenArguments does and calculated the  
sum and length at the same time without building an intermediate  
Array at all. median could be similarly special cased but that would  
be a pain in the ass to do faster and it isn't really very commonly  
used anyway. Note that using sum() currently introduces a dependency  
on MochiKit.Iter, but I'd be open to moving it to MochiKit.Base and  
specialize based upon the input type and iter availability like map()  
does.

The empty list cases should be handled somehow.. mean obviously  
returns NaN because it's doing divide by zero, but median much less  
obviously returns NaN: (undefined + undefined)/2. I'm not sure if  
people would expect 0.0 or an error to be thrown, I doubt NaN is  
desired though.

Renaming mean to average or avg might make sense. I think more people  
are familiar with the term average.

-bob


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"MochiKit" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/mochikit
-~----------~----~----~----~------~----~------~--~---

Reply via email to