Let's say I have two fractions: a/b and c/d, where a,b,c,d are all integers greater than 0. Is it safe to check their equality using the following function?:
bool are_equal_fractions(int a, int b, int c, int d) {
return (static_cast<double>(a) / b == static_cast<double>(c) / d);
}
According to another question: can I compare two fractions if both have denominator with power of 2 I can use this method when both denominators are powers of 2, but what about more generic case?
Although every int can be represented as a double, many int ratios cannot be represented exactly, and very similar but slightly different fractions may round to the same double.
Consider a=2147483647, b=2147483646, c=2147483646, d=2147483645. The denominator of 2147483646/2147483645 will be a multiple of 5, even in its lowest terms. The denominator of 2147483647/2147483646 is not a multiple of 5, so they are not equal.
cout << are_equal_fractions(2147483647, 2147483646, 2147483646,
2147483645) << endl;
outputs "1".
In general, equal fractions in this pattern would mean:
(i+2)/(i+1) == (i+1)/i
i*(i+2) == (i+1)*(i+1)
i^2 + 2*i == i^2 + 2*i + 1
0 == 1
which has no solution.
The smallest counter-example following this pattern is are_equal_fractions(67114658,67114657,67114657,67114656)
. I do not think any other pattern could have a closer non-equal ratio, so it is probably safe for values less than this case.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments