浮点比较可能比普通整数比较更昂贵,尤其是在您没有专用浮点硬件的情况下。
幸运的是,在比较浮点数时可以使用整数比较,在某些情况下:
1) 这仅在使用 IEEE754 浮点格式时有效。2) 它不适用于 NaN:s。
访问底层表示是欠精细的行为,因为 C 语言没有指定它使用哪种浮点格式。
无论如何,诀窍在于它仅在浮点数具有相同符号时才有效。而且,在这种情况下,比较两个负浮点数的整数表示与比较浮点数本身是相反的。
我没有对下面的代码进行性能测量,但很可能它比您的原始代码更快。如果有的话,请让我知道性能提升!
int compareAB(float a_orig, float b_orig)
{
/* Get the underlying representation of A and B. */
long a = *(unsigned long *)&a_orig;
long b = *(unsigned long *)&b_orig;
if (a < 0)
{
if (b < 0)
{
/* Both are negative. The order of the integer representation is
* the OPPOSITE of the order of the floating-point value. */
if (a > b)
{
return -1;
}
else if (a < b)
{
return 1;
}
else
{
return 0;
}
}
else
{
/* A is negative, B isn't => A is smaller. */
return -1;
}
}
else if (b < 0)
{
/* B is negative, A isn't => B is smaller. */
return 1;
}
else
{
/* Both are positive. */
if (a > b)
{
return 1;
}
else if (a < b)
{
return -1;
}
else
{
return 0;
}
}
}
您可以使用以下方法进行测试:
#include <stdio.h>
float values[] = {-100.0F,
-50.0F,
0.0F,
50.0F,
100.0F };
void test(float a, float b)
{
const char * p = 0;
printf("%f is ", a);
switch (compareAB(a, b))
{
case -1: p = "smaller than"; break;
case 0: p = "equal to"; break;
case 1: p = "greater than"; break;
}
printf("%s %f\n", p, b);
}
int main(void)
{
int i;
for (i = 0; i < sizeof(values)/sizeof(values[0]); ++i)
{
int j;
for (j = 0; j < sizeof(values)/sizeof(values[0]); ++j)
{
test(values[i], values[j]);
}
}
}
它提供与使用原始代码时相同的输出,即:
-100.000000 is equal to -100.000000
-100.000000 is smaller than -50.000000
-100.000000 is smaller than 0.000000
-100.000000 is smaller than 50.000000
-100.000000 is smaller than 100.000000
-50.000000 is greater than -100.000000
-50.000000 is equal to -50.000000
-50.000000 is smaller than 0.000000
-50.000000 is smaller than 50.000000
-50.000000 is smaller than 100.000000
0.000000 is greater than -100.000000
0.000000 is greater than -50.000000
0.000000 is equal to 0.000000
0.000000 is smaller than 50.000000
0.000000 is smaller than 100.000000
50.000000 is greater than -100.000000
50.000000 is greater than -50.000000
50.000000 is greater than 0.000000
50.000000 is equal to 50.000000
50.000000 is smaller than 100.000000
100.000000 is greater than -100.000000
100.000000 is greater than -50.000000
100.000000 is greater than 0.000000
100.000000 is greater than 50.000000
100.000000 is equal to 100.000000