C: How to wrap a float to the interval [-pi, pi)

前端 未结 15 947
死守一世寂寞
死守一世寂寞 2020-11-28 21:47

I\'m looking for some nice C code that will accomplish effectively:

while (deltaPhase >= M_PI) deltaPhase -= M_TWOPI;
while (deltaPhase < -M_PI) deltaP         


        
15条回答
  •  伪装坚强ぢ
    2020-11-28 22:34

    A two-liner, non-iterative, tested solution for normalizing arbitrary angles to [-π, π):

    double normalizeAngle(double angle)
    {
        double a = fmod(angle + M_PI, 2 * M_PI);
        return a >= 0 ? (a - M_PI) : (a + M_PI);
    }
    

    Similarly, for [0, 2π):

    double normalizeAngle(double angle)
    {
        double a = fmod(angle, 2 * M_PI);
        return a >= 0 ? a : (a + 2 * M_PI);
    }
    

提交回复
热议问题