c++ - 这是环绕角度的正确代码吗 (-180,180]

标签 c++ c angle

我正在读这个 book我遇到了这个函数 wrapPi()。我知道如何包角,但这段代码到底在做什么

float wrapPi ( float theta ) {
// Check if already in range. This is not strictly necessary,
// but it will be a very common sit u a t i o n . We don ’ t want to
// incur a speed hit and perhaps floating precision loss if
// it’s not necessary
if ( fabs( theta ) <= PI ) {
    // One revolution is 2PI .
    const float TWOPPI = 2.0f∗PI ;
    // Out of range. Determine how many ”revolutions”
    // we need to add .
    float revolutions = floor (( theta + PI ) ∗ ( 1.0f /TWOPPI )) ;
    // Subtract it off
    theta −= revolutions ∗ TWOPPI ;
}
return theta;
}

最佳答案

这一行有错误:

if ( fabs( theta ) <= PI ) {

应该是

if ( fabs( theta ) > PI ) {

这是唯一不能只返回 theta 的现有值的情况. 其余if语句计算出您需要添加或添加多少次 减去 2*PI 以找到等于 theta 的角度在正确的范围内。

我个人更喜欢为 if (theta <= -PI) 编写单独的代码块 和 if (theta > PI) ,但这可能是由于遇到的偏见 fabs 的执行非常缓慢过去。

关于c++ - 这是环绕角度的正确代码吗 (-180,180],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948968/

相关文章:

java - 从 Win32 应用程序中检索 Java 对象 (List)

c - 两个信号量不通信

html - Emscripten - 如何使用 emcc 而不是 gcc 来使用我的 makefile?

r - 两个几乎相同的向量之间的角度

python - 计算三角形Python的角度

algorithm - 计算圆圈中的点 - 步长?

c++ - ARM STM32需要兼容的编译器

C++ 过滤文本文件中的内容

c++ - 我怎样才能将一个类的填充字节归零?

C语言,串口阅读器