Square root of negative zero

2019-04-23 14:35发布

问题:

Under g++ version 4.8.0 (32-bit mingw), the square root of -0.0 (binary representation 0x8000000000000000) is NAN. But I could have sworn that earlier versions (I'm not sure which, but the last time I ran my full test suite) returned simply 0.0, which seems more sensible to me.

Is this right? Has something in the C++ standard changed, or is this a g++ change?

回答1:

This is a non-standard* behavior of the MinGW environment (that I have also observed, indirectly, through a customer for whom the software I work on was failing unexpectedly).

You may have seen the correct result for sqrt(-0.), i.e. -0., with a higher optimization level where the value was computed correctly at compile-time, or with a previous version of the run-time in which the bug was not present.

I ended up defining my own “fixed” sqrt() as:

double mysqrt(double x) {
  if (x == 0.) return x; else return sqrt(x);
}

(*) IEEE 754 defines sqrt(-0.) as -0.. A C or C++ compiler does not have to implement IEEE 754 for floating-point arithmetic, but GCC tries to (and in this particular instance, fails).