0

I want a JavaScript function that reduces an array of numbers to an average of those numbers. My function code looks like this:

Array.prototype.avg = function(ignoreZero = false) {
    return (this.reduce(function(a, b) {
        return a + b;
    }) / (this.length));
};

But I know that this might result in inaccurate values for rational numbers with decimal points due to the way numbers are handled in JavaScript, and so the average may be inaccurate.

I'm not exactly clear on the details as to why this problem exists (I don't really understand floating point), but I would like to know if there is an easy solution to this.

It seems like most people just recommend multiplying the decimal component away from rational numbers, but since I don't ever know how many decimals a rational number may have, this solution won't work.

Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • 1
    Given numbers `[2, 3, 5]` what average value would you expect? – georg Feb 10 '18 at 19:22
  • You can't have infinite precission with finite memory (and finite time), unless you decide to handle the computation in an abstract way (like wolfram alpha or math calculators). What are you exactly trying to achieve? – Giulio Bambini Feb 10 '18 at 19:22
  • you can try multiplying the decimal to an integer, so let's say 0.001 you do * 1000 and then do your calculations with it. – Orry Feb 10 '18 at 19:22
  • @OrryVandermeulen Non float values are also not precise in javascript. – Giulio Bambini Feb 10 '18 at 19:23
  • ah thanks. I'd like accuracy to 2 decimal places – Zach Smith Feb 10 '18 at 19:23
  • What is the meaning of Array, prototypes, reduce function, Etc., regarding to your question's title? – Ele Feb 10 '18 at 19:25
  • The sum of the array values is calculated via reduction. The function is just added to Array's prototype because in this specific case it is convenient to call this way. @Ele. Does that answer your question? – Zach Smith Feb 10 '18 at 19:31
  • @GiulioBambini - if I multiple the sum of the array by 1000, and then divide by the length of the array, and then divide by 1000, will that give me accurate results? – Zach Smith Feb 10 '18 at 19:33
  • @ZachSmith I understand that, however, you could ask in a different way without all of that code imho. – Ele Feb 10 '18 at 19:34
  • @ZachSmith The problem isn't with just decimal places. This stuff has been already covered on So multiple times. I recommend this: http://floating-point-gui.de/ – Giulio Bambini Feb 10 '18 at 19:35

1 Answers1

1

The js community has a solution for every inherent feature of javascript so... Bam there's a library for that.

http://mathjs.org/docs/getting_started.html

Specifically big numbers http://mathjs.org/docs/datatypes/bignumbers.html

Jacob
  • 87
  • 7