Floating Point Fun
by havoc
Elijah, I
think you may be even more screwed than you think. I recently went
through some pain because I assumed that “a == b” would do a bitwise
comparison of two doubles a and b. It turns out that this isn’t true,
and I bet that even if the compiler doesn’t drop the i from “i+a>i”
it’s still not a meaningful test if you’re looking for bitwise equality.
Depending on the goal, you may have to write something like:
double d1 = i + a; double d2 = i; if ((*(uint64_t*)(unsigned char*)&d1) != (*(uint64_t*)(unsigned char*)&d2)) printf ("doubles are not bitwise equal\n");
I was told the reason “d1 != d2” doesn’t work for bitwise compare is
that the x86 floating point registers are 80 bit so if one double is
in a register and one in memory as 64-bit, then you get weirdness.
Don’t know if this matters for your application, but I found it
surprising. (And it does matter for D-BUS since I wanted to check
whether the right bits were marshaled/demarshaled.)
(This post was originally found at http://log.ometer.com/2005-01.html#15)