Search code examples
c++floating-pointprecisionieee-754

Why does C or C++ “-0” not produce a floating-point −0?


I am trying to collect some edge cases for floating-point arithmetic. The thing is, my attempt with printf is not showing me what I want:

#include <cmath>
#include <stdio.h>
#include <complex>

int main() {
    double x = -0;
    auto y = sqrt(x);

    printf("x %f y %f \n", x, y);

    return 1;
}

Per IEEE, squareRoot(-0) is -0, but this will print out both x and y to be 0.

Any suggestions on how I can achieve what I want? Would it be through compiler flags or something different?


Solution

  • 0 is an integer constant, so -0 is also an integer which is still 0.

    To get a negative zero, using a floating point constant.

    double x = -0.0;