Additional Math functions
Waldemar Horwat
waldemar at google.com
Fri Oct 2 20:23:36 UTC 2015
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
More information about the es-discuss
mailing list