Suppose I have a sum as follows, where n
is any positive integer.
let sum = 0;
for (let i = 0; i < n; ++i) {
sum += (1/n);
}
This sum should always equal 1, but with JS floating point weirdness, it sometimes does not. Thus, I have been using Number.EPSILON
when comparing sum
to 1, as follows:
function sumIsEqualToOne(sum) {
return Math.abs(1 - sum) < Number.EPSILON;
}
per the example on MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON).
This doesn't always work though, as for n = 7
, 1 - sum === Number.EPSILON
, so sumIsEqualToOne
returns false
.
Is my original assumption incorrect, and sum
is not actually always equal to 1 here? Does (1/7)+(1/7)+(1/7)+(1/7)+(1/7)+(1/7)+(1/7) !== 1
?