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

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

    Here is a version for other people finding this question that can use C++ with Boost:

    #include 
    #include 
    
    template
    inline T normalizeRadiansPiToMinusPi(T rad)
    {
      // copy the sign of the value in radians to the value of pi
      T signedPI = boost::math::copysign(boost::math::constants::pi(),rad);
      // set the value of rad to the appropriate signed value between pi and -pi
      rad = fmod(rad+signedPI,(2*boost::math::constants::pi())) - signedPI;
    
      return rad;
    } 
    

    C++11 version, no Boost dependency:

    #include 
    
    // Bring the 'difference' between two angles into [-pi; pi].
    template 
    T normalizeRadiansPiToMinusPi(T rad) {
      // Copy the sign of the value in radians to the value of pi.
      T signed_pi = std::copysign(M_PI,rad);
      // Set the value of difference to the appropriate signed value between pi and -pi.
      rad = std::fmod(rad + signed_pi,(2 * M_PI)) - signed_pi;
      return rad;
    }
    

提交回复
热议问题