开发者

C++ sin() returns incorrect results

开发者 https://www.devze.com 2023-02-08 22:34 出处:网络
i have this piece of code bool Position::HasInLine(const Unit * const target, float distance, float width) const

i have this piece of code

bool Position::HasInLine(const Unit * const target, float distance, float width) const
{
    if (!HasInArc(M_PI, target) || !target->IsWithinDist3d(m_positionX, m_positionY, m_positionZ, distance))
        return false;
    width += target->GetObjectSize();
    float angle = GetRelativeAngle(target);
    float absSin = abs(sin(angle));
    return abs(sin(angle)) * GetExactDist2d(target->GetPositionX(), target->GetPositionY()) < width;
}

Problem i ran into is, that when i debug with gdb and try "p sin(angle)" it returns weird values - for angle 1.51423 it states that sin = 29 (so yes, i am putting in radians :-) ). More weird is, that when i try "p absSin" it alway开发者_如何学Pythons returns 0, and yes, i was on next line, so the "float absSin = abs(sin(angle))" line was already done. Originaly there wasnt even included cmath, but the M_PI const was returning correct value, though i added #include at the start of the .cpp file just to make sure, but nothing changed.

If it helps, im using linux kernel 2.6.26-2-xen-amd64 Any ideas?


The function abs (as defined in cstdlib) always takes an integer and returns an integer. When dealing with doubles, you should be using fabs instead.

Another version of abs is defined in cmath (#include <cmath>). It is overloaded to accept (and return) both integers and doubles.

You may wish to double-check which version you are using.


shouldn't you be using fabs and not abs? abs takes ints and returns only ints


"for angle 1.51423 it states that sin = 29"

That's most probably an error of observation, not an error of the sin function.

The result should be in range -1 through +1.

Cheers & hth.,

0

精彩评论

暂无评论...
验证码 换一张
取 消