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

前端 未结 15 940
死守一世寂寞
死守一世寂寞 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:18

    I would do this:

    double wrap(double x) {
        return x-2*M_PI*floor(x/(2*M_PI)+0.5);  
    }
    

    There will be significant numerical errors. The best solution to the numerical errors is to store your phase scaled by 1/PI or by 1/(2*PI) and depending on what you are doing store them as fixed point.

提交回复
热议问题