Really? Negative zero?!

double Vector2D::GetFacingAngle(const Vector2D& target, const Vector2D& source) {
    a2de::Vector2D facingVec(Vector2D(source) - Vector2D(target));

    //Negating 'y' argument to account for flipped nature of 'y' screen coordinates.
    double result = std::atan2(-facingVec.GetY(), facingVec.GetX());

    //Which causes -0.0 as a possible result when source is right of target at the same 'y' coordinate.
    if(a2de::Math::IsEqual(result, -0.0)) return 0.0;
    return result;

Is this a common behavior? (Similar to subtracting 'y' coordinates for 'up' movement in screen coordinates contrary to Cartesian coordinates.)

  • 2
    \$\begingroup\$ BTW, you shouldn't need to care whether it comes out negative zero or positive zero. Any further floating point math you do on the result should work correctly anyway. \$\endgroup\$ – Nathan Reed Aug 7 '12 at 0:12
  • 1
    \$\begingroup\$ It doesn't matter at all, because -0.0 == 0.0 according to IEEE 754 \$\endgroup\$ – Maik Semder Aug 7 '12 at 11:44
  • \$\begingroup\$ @MaikSemder From an aesthetic standpoint it does (like...displaying the angle to the screen) \$\endgroup\$ – Casey Aug 7 '12 at 12:32
  • \$\begingroup\$ @Casey I see, no reason to touch the math code though. The math code works fine. This is a GUI problem. Make the values user friendly in the UI code before you show it on screen, rather than polluting the basic math code with unnecessary comparisons. \$\endgroup\$ – Maik Semder Aug 7 '12 at 12:42

What you're seeing is a signed zero, which is a possibility in certain systems of number representation, including the IEEE standard used for C++ floating point representation, even though it isn't really a thing in "ordinary" mathematics.

The link contains some notes on behavior and handling of the occurrence, although beyond that it's not entirely clear to me what you're asking, specifically -- it's not a bug with atan2 though. In fact, the wiki article on the function notes that the relevant Intel assembly instruction (FPATAN), which you're likely generating here, will produce a negative zero when first parameter in negative zero but the second is positive zero. Your explicit negation of your vector's Y component could easily produce such a scenario.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.