"user923005" <
[email protected]> a écrit dans le message de (e-mail address removed)...
qsort is not guaranteed to work if the comparison function does not define a
full order on the whole set of values in the array. This function is
inappropriate for sorting an array. A simplistic function that performs
straight floating point comparisons is not appropriate either :
int compare_doubles(const double *pa, const double *pb) {
return (*pb < *pa) - (*pa < *pb);
}
it defines a complete order on all doubles except NaNs.
it does not either distinguish 0.0 and -0.0.
Designing a comparison function to property sort on floating point values is
non trivial. I wonder why none is provided in math.h.
For *sorting* floating point, I use this trick from Terje Mathisen
(obviously, you have to write one of these for each and every distinct
floating point that you use):
#include <assert.h>
typedef unsigned long uint32;
#define SB_MASK32 0x80000000UL
#ifdef _MSC_VER
typedef unsigned __int64 uint64;
typedef __int64 sint64;
#define SB_MASK64 0x8000000000000000ui64
#else
typedef unsigned long long uint64;
typedef long long sint64;
#define SB_MASK64 0x8000000000000000ULL
#endif
extern uint32 float2key(float f);
uint64 double2key(double d);
uint32
float2key(float f)
{
uint32 sign,
mant,
mask;
assert(sizeof(float) == sizeof(uint32));
mant = *(uint32 *) & f; /* Load float as array of bits */
sign = mant & SB_MASK32; /* Isolate the leading sign bit */
mant ^= SB_MASK32; /* Invert the sign bit, making + > -
*/
mask = sign - (sign >> 31); /* Either 0 or 0x7fffffff */
mant ^= mask; /* Invert exp and mant if negative */
return mant;
}
uint64
double2key(double d)
{
uint64 sign,
mant,
mask;
assert(sizeof(double) == sizeof(uint64));
mant = *(uint64 *) & d; /* Load float as array of bits */
sign = mant & SB_MASK64; /* Isolate the leading sign bit */
mant ^= SB_MASK64; /* Invert the sign bit, making + > -
*/
mask = sign - (sign >> 63); /* Either 0 or 0x7fffffffffffffff */
mant ^= mask; /* Invert exp and mant if negative */
return mant;
}
But for comparison (e.g. in a database operation) I use the function
that I presented (actually, one rather similar to that)