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.