Additional Math functions
Eli Perelman
eli at eliperelman.com
Fri Oct 2 20:30:27 UTC 2015
In addition, using reduce just to sum array elements forces a function
execution for every element. May not be bad for a minimal count of
elements, but doing statistical work on larger collections would benefit
from having an optimized summation.
Eli Perelman
On Fri, Oct 2, 2015 at 3:23 PM, Waldemar Horwat <waldemar at google.com> wrote:
> On 10/01/2015 23:10, Sebastian Zartner wrote:
>
>> While Math.sum() and Math.mean() currently don't exist, they can easily
>> be polyfilled:
>> See
>> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Sum_all_the_values_of_an_array
>> for summarizing the values of an array and the following code for building
>> the average of the array values:
>>
>> let arr = [0, 1, 2, 3];
>> let total = arr.reduce(function(a, b) {
>> return a + b;
>> });
>> let mean = total / arr.length;
>>
>> Calculating the variance and standard deviation would require a bit more
>> code, though are also easy to polyfill.
>> Non-the-less I can see the need for having standard functions for this.
>>
>> Sebastian
>>
>
> Yes, Math.sum can be polyfilled, but doing so if you want accurate answers
> takes a fair amount of care. The code above is pretty bad as a polyfill
> because it sometimes produces highly inaccurate answers. For example, if
> arr = [1, 1e18, -1e18], then this polyfill will return the incorrect value
> 0 for total, while a more careful implementation would return 1.
>
> Waldemar
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20151002/408ff41a/attachment.html>
More information about the es-discuss
mailing list