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

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

    There is also fmod function in math.h but the sign causes trouble so that a subsequent operation is needed to make the result fir in the proper range (like you already do with the while's). For big values of deltaPhase this is probably faster than substracting/adding `M_TWOPI' hundreds of times.

    deltaPhase = fmod(deltaPhase, M_TWOPI);
    

    EDIT: I didn't try it intensively but I think you can use fmod this way by handling positive and negative values differently:

        if (deltaPhase>0)
            deltaPhase = fmod(deltaPhase+M_PI, 2.0*M_PI)-M_PI;
        else
            deltaPhase = fmod(deltaPhase-M_PI, 2.0*M_PI)+M_PI;
    

    The computational time is constant (unlike the while solution which gets slower as the absolute value of deltaPhase increases)

提交回复
热议问题