Square root of negative zero

早过忘川 提交于 2020-01-13 08:48:12

问题


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).



来源:https://stackoverflow.com/questions/19232157/square-root-of-negative-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!