How can I get the best accurate result?
7 replies
For best precision / precision, you want to do your multiplications before your divisions. As you imply, you will want to use something twice as large as an int:
int64_t d = (int64_t) a * (int64_t) b;
d /= c;
You don't need both throws, but they might make it clearer.
Note that if c is small enough, then d can still be larger than int. This may or may not be a problem for you. If you are sure that it is not you can reset to the end at the end.
+3
a source to share
You can always do an explicit overflow check on * b:
long long e = (long long) a * (long long) b;
if (e <= INT_MAX) {
d = e / c;
} else {
d = a * (b / c);
}
Of course, this only works for non-negative a, b, c. If they can be negative, you will need to check INT_MIN as well.
[Update] You can also check which of a and b is larger, and thus loses less precision when divided by c:
if (a >= b) {
d = a / c * b;
} else {
d = a * (b / c);
}
+1
a source to share