Take the 2-minute tour ×

Say I have two rational fractions a/b and c/d that are equal. a, b, c, and d can all be represented as 32 bit signed integers. if i do division with 64 bit floating point numbers will a/b == c/d always?

share|improve this question
If you're testing for equality, you could just use 64-bit integers and compare (ad) with (bc), and avoid the whole floating point rounding issue altogether. –  cHao Aug 27 '12 at 20:23
1/2 and 3/6 for example is going to differ for sure. –  Fakrudeen Aug 28 '12 at 7:38
1/2 and 3/6 are not going to differ, why would they? They will be both exactly (1/2) whatever precision used (float double extended...). double(1)/double(3) and double(5)/double(15) would also lead to the same result as long as num.and den. are converted exactly, IEEE / is such that result is exact fraction rounded according to rounding rules (and mode). If intermediate extended precision is used, then a 2nd rounding is performed to double... double(1/extended(3)) might differ from 1/double(3)... If both fractions pass through the same rounding stages though, result should be the same. –  aka.nice Aug 28 '12 at 17:10

1 Answer 1

up vote 4 down vote accepted

There are cases where compiler optimizations will prevent the equality from being true even if the results are guaranteed identical. The original x86 floating point operations are performed on 80-bit registers; if you compare one of those to a stored 64-bit value it will probably compare unequal.

share|improve this answer
it would be nice to be able to see some code that would show this problem. i've tried doing this in java and can't seem to force a 64 bit comparison with an 80 bit value. –  benmmurphy Aug 27 '12 at 20:41
There are multiple compilers for Intel targets, and they do not all implement floating-point operations with 80-bit values. –  Eric Postpischil Aug 27 '12 at 20:55
@EricPostpischil, you're right - modern compilers may implement floating point with SSE and avoid the 80-bit registers altogether. Since the question asked about "always" I felt a single counter-example was enough. –  Mark Ransom Aug 27 '12 at 21:01
@benmmurphy, it's possible that Java doesn't suffer from this problem, either because it doesn't use the older 80-bit floating point instructions or because it always stores the result before comparing it. –  Mark Ransom Aug 27 '12 at 21:06
Java does not give the implementation latitude to use extra precision the way C does. It is not required to “store” the result before comparing; it is simply required to calculate with double precision (given double-precision operands), period. –  Eric Postpischil Aug 27 '12 at 23:20

Your Answer


