Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
Quang Thinh Ha Avatar asked Sep 03 '25 03:09

Quang Thinh Ha


1 Answers

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;
like image 101
dbush Avatar answered Sep 04 '25 17:09

dbush