Search code examples
cfloating-pointdoubleieee-754low-level

Is there a neutral element in IEEE754 with regards to addition


Consider the following code snippet

double id = ?;
double res;
long unsigned *res_u = (long unsigned*)&res;

long unsigned i;
for (i = 0; i < (long unsigned)-1; i++){
    double *d1 = (double*)&i;
    res = id + *d1;
    assert(*res_u == i);
}

My question: Is there a value for id, so that the assertion holds for all i? In other words for the mathematicians among us: is there double that is the neutral element for addition?


Solution

  • -0. is paradoxically the floating-point value that serves as neutral for addition.

    +0. nearly is, but -0. + (+0.) makes +0..

    Apart from that, +inf + (-0.) makes +inf, -inf + (-0.) makes -inf, and NaN + (-0.) makes NaN.