3 ms·
I had a fun floating-point related bug the other day: I wanted to sort a list of doubles in C, and my comparison function was in essence: static int compar
by rwmj 10y ago
I had a fun floating-point related bug the other day: I wanted to sort a list of doubles in C, and my comparison function was in essence:
static int compare (void *dpa, void *dpb)
{
return *(double*)dpa - *(double*)dpb;
}
The doubles represented times in nanoseconds, and the program failed to sort properly when the total runtime was larger than (IIRC) 2 seconds. I wonder if you can work out why.
(Spoiler alert) the fix was:
https://github.com/libguestfs/libguestfs/commit/1f4a0bd90df35df56eb86c2386d801b51828cb22 https://github.com/libguestfs/libguestfs/commit/1f4a0bd90df3...
- Bromskloss 10y agoHow come the argument types are void* instead of double*?
- CamperBob2 10y agoYour fix requires a lot of mental CPU cycles on the part of whoever reads the code. Are you sure it wouldn't have been better to do it the simple, obvious way? double a = *(double *) dpa; double b = *(double *) dpb; if (a > b) return 1; if (b < a) return -1; return 0;
- rwmj 10y agoYup I think you are right -- the (fixed) code is very obscure now.
- huhtenberg 10y agoI think it's actually quite elegant. The issue is that it always does two comparisons, even when one would suffice.
- Someone 10y agoDepending on how the compiler computes a>b, it may be branchless, though, and I expect that to be more important on modern CPUs.
- deleted 10y ago[deleted]
- titzer 10y agoThat code returns 0 for all NaN inputs.
- CamperBob2 10y agoTrue enough, but if you're passing NaNs to qsort(), something has already gone wrong in your professional life.
- sijoe 10y agoOh my gosh ... the fortran computed goto is back ... See http://www.lahey.com/docs/lfprohelp/F95ARComputed_GOTOStmt.htm http://www.lahey.com/docs/lfprohelp/F95ARComputed_GOTOStmt.h...