This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Relying on precise integer calculation with double


gcc really, really ought to specify more precisely what floating point
semantics one can depend on.

Bug 323, paraphrased, says "floating point comparisons return random
numbers".  Ok, that's pumping it a bit, but consider the following
qsort comparison function right out of K&R 2nd Edition page 121:

int numcmp(char *s1, char *s2)
{
    double v1, v2;

    v1 = atof (s1);
    v2 = atof (s2);
    if (v1 < v2)
        return -1;
    else if (v1 > v2)
        return 1;
    else
        return 0;
}

[Ignore NaNs, strings that don't yield numbers, missing consts, and
the silliness of calling atof inside this function.]

Bug 323 says that the two comparisons can return results that are
inconsistent from a mathematical point of view.  (And, in principle,
that even with identical arguments one could get different results
for calls.)  In either case, qsort with such a function is undefined
behaviour according to C99.  And in practice, bad things do happen
if the comparison function returns inconsistent results, for example
on Solaris

It doesn't look like the C99 macros isless, etc., can resolve the
issue.  One would need a single call producing the final ordering
result, or an int from which it could be derived.

So there.  One cannot sort floating point values with qsort under
gcc if Bug 323 is the final word on semantics.  In practice it
works just fine.

Morten


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]