0

How do I check if my variable double x is equal to -0.0?

mrk
  • 3,061
  • 1
  • 29
  • 34
  • 2
    @IlyaKogan Well not never, right? Just not reliably. If I did `0.0 == 0.0` it would evaluate to true, right? – BWG Nov 30 '14 at 22:31
  • Use [`std::signbit`](http://en.cppreference.com/w/cpp/numeric/math/signbit) and ordinary comparison with `0`? – Kerrek SB Nov 30 '14 at 22:32
  • @IlyaKogan: Nonsense. – Lightness Races in Orbit Nov 30 '14 at 22:52
  • @Will: No, that won't work. You need a `reinterpret_cast` (to do that in C requires casting pointers). But why would C be lacking `signbit`? – Ben Voigt Nov 30 '14 at 23:21
  • 1
    You may find ["What operations and functions on +0.0 and -0.0 give different arithmetic results?"](http://stackoverflow.com/questions/25332133/what-operations-and-functions-on-0-0-and-0-0-give-different-arithmetic-results) useful. – chux - Reinstate Monica Nov 30 '14 at 23:43
  • @Will I guess you are thinking of `*(int64_t *)&x`, rather than `(int64_t)x` – M.M Nov 30 '14 at 23:59
  • @Will: Did you actually test on negative zero, or just some other negative values? – Ben Voigt Dec 01 '14 at 02:53
  • @Will: Your code FAILS. Demo: http://rextester.com/PQQUE83634 Same results on clang and gcc, and in both C and C++ modes. – Ben Voigt Dec 01 '14 at 02:59
  • @MattMcNabb: Of course `*(int64_t *)&x` would violate strict aliasing. The library function is definitely the way to go. – Ben Voigt Dec 01 '14 at 03:01
  • @Will: In fact, it doesn't distinguish sign of any number with magnitude less than 1: http://rextester.com/CSDV23001 – Ben Voigt Dec 01 '14 at 03:13
  • @Will the C standard requires that floating point zero and negative zero both become `+0` after doing `(int64_t)x` . (In fact 2's complement systems, which most of us probably have, do not even have negative zero for integer types). I'd guess your example that "works as-is" actually casts some extremely small negative but non-zero example. – M.M Dec 01 '14 at 03:28
  • @Will: Why? Conversion to integer truncates toward zero. I'll say it again: You need a reinterpret_cast here, not a conversion. – Ben Voigt Dec 01 '14 at 03:38

0 Answers0