C++ sin() 返回不正确的结果
我有这段代码,
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;
}
我遇到的问题是,当我用 gdb 调试并尝试“p sin(angle)”时,它返回奇怪的值 - 对于角度 1.51423,它指出 sin = 29 (所以是的,我输入弧度:-) )。更奇怪的是,当我尝试“p absSin”时,它总是返回0,是的,我在下一行,所以“float absSin = abs(sin(angle))”行已经完成。 最初甚至没有包含 cmath,但 M_PI const 返回正确的值,尽管我在 .cpp 文件的开头添加了 #include 只是为了确保,但没有任何改变。
如果有帮助,我使用 linux 内核 2.6.26-2-xen-amd64 有什么想法吗?
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 always 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数
abs
(如cstdlib
中定义)始终接受一个整数并返回一个整数。处理double
时,您应该使用fabs
来代替。abs
的另一个版本在cmath
中定义 (#include
)。它被重载以接受(并返回)整数和双精度数。您可能希望仔细检查您正在使用的版本。
The function
abs
(as defined incstdlib
) always takes an integer and returns an integer. When dealing withdouble
s, you should be usingfabs
instead.Another version of
abs
is defined incmath
(#include <cmath>
). It is overloaded to accept (and return) both integers and doubles.You may wish to double-check which version you are using.
你不应该使用 fab 而不是 abs 吗? abs 接受整数并仅返回整数
shouldn't you be using fabs and not abs? abs takes ints and returns only ints
“对于角度 1.51423,它指出 sin = 29”
这很可能是观察错误,而不是 sin 函数的错误。
结果应在 -1 到 +1 范围内。
干杯&呵呵,,
"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.,