On 21-Jun-06, at 5:30 PM, Bob Ippolito 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.

I'll work on mean. Moving sum seems like way more work than just  
writing a loop. Instead of renaming mean, what about aliasing it (and  
note that in the docs)? Here's what JavaScript does with similar  
functions that expect arguments:

 >>> Math.min()
Infinity
 >>> Math.max()
-Infinity
 >>> Math.ceil()
NaN
 >>> Math.cos()
NaN

And MochiKit:

 >>> listMin()
TypeError: Undefined value [...]
 >>> listMax()
TypeError: Undefined value [...]
 >>> listMin([])
null
 >>> listMax([])
null

I think listMin and listMax follow Math.min and .max. mean and median  
should probably return NaN.

--~--~---------~--~----~------------~-------~--~----~
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