简体   繁体   中英

Are two doubles of equal value guaranteed to have the same bit pattern?

在C中,是否保证两个值相等的双精度数( double1 == double2 )将具有相同的位模式?

There is no such guarantee.

For example, in IEEE floating point format , there exists the concept of negative 0. It compares equal to positive 0 but has a different representation.

Here's an example of that:

#include <stdio.h>

int main()
{
    unsigned long long *px, *py;
    double x = 0.0, y = -0.0;
    px = (unsigned long long *)&x;
    py = (unsigned long long *)&y;

    printf("sizeof(double)=%zu\n",sizeof(double));
    printf("sizeof(unsigned long long)=%zu\n",sizeof(unsigned long long));

    printf("x=%f,y=%f,equal=%d\n",x,y,(x==y));
    printf("x=%016llx,y=%016llx\n",*px,*py);

    return 0;
}

Output:

sizeof(double)=8
sizeof(unsigned long long)=8
x=0.000000,y=-0.000000,equal=1
x=0000000000000000,y=8000000000000000

EDIT:

Here's a revised example that doesn't rely on type punning:

#include <stdio.h>

void print_bytes(char *name, void *p, size_t size)
{
    size_t i;
    unsigned char *pdata = p;
    printf("%s =", name);
    for (i=0; i<size; i++) {
        printf(" %02x", pdata[i]);
    }
    printf("\n");
}

int main()
{
    double x = 0.0, y = -0.0;

    printf("x=%f,y=%f,equal=%d\n",x,y,(x==y));
    print_bytes("x", &x, sizeof(x));
    print_bytes("y", &y, sizeof(y));

    return 0;
}

Output:

x=0.000000,y=-0.000000,equal=1
x = 00 00 00 00 00 00 00 00
y = 00 00 00 00 00 00 00 80

You can see here the difference in representation between the two. One has the sign bit set while the other doesn't.

Yes, with the exception of zero. There is only one way to represent a particular IEEE float or double value. If there were two ways to represent the same value then that would be wasteful and the IEEE formats are very efficient.

Zero is a special case because there are positive and negative values of zero and they will compare equal, and they are equal for most purposes. There are a few rare cases (1/0) where they will give different results - positive versus negative infinity.

The previous answer focused unnecessarily on the zero case and failed, as far as I can tell, to answer the case for the other 4 billion floats and 16 billion billion doubles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM