Rounding Error On Percent Of Total And Back
A and B are integers. Is it certain, with all the complexities of rounding errors in JavaScript, that: (A/(A+B))*(A+B) === A This is to say that if the user enters 10, and 20 for A
Solution 1:
Well I set out to answer my own question with some easy scripting.
Here's what I ran:
var maxDifference = 0;
var assert = function (a, b) {
var derivedA = (a/(a+b))*(a+b);
if (!(derivedA === a) && (a - derivedA) > maxDifference) {
console.log('----\nFound new biggest difference');
console.log('a:', a);
console.log('b:', b);
console.log('difference:', (a - derivedA));
maxDifference = a - derivedA;
}
}
for (var a = 1; a < 10000000; a++) {
for (var b = 1; b < 10000000; b++) {
assert(a, b);
}
}
console.log('Max Difference:', maxDifference);
What I found is that there CAN be a difference. That difference is something like (2^n)*Number.EPSILON
where n
is (so far) 15. This is about: 3.9968028886505635e-15
Rounding seems to be a safe way to reliably get back to the original int.
Post a Comment for "Rounding Error On Percent Of Total And Back"