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

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

    I encountered this question when searching for how to wrap a floating point value (or a double) between two arbitrary numbers. It didn't answer specifically for my case, so I worked out my own solution which can be seen here. This will take a given value and wrap it between lowerBound and upperBound where upperBound perfectly meets lowerBound such that they are equivalent (ie: 360 degrees == 0 degrees so 360 would wrap to 0)

    Hopefully this answer is helpful to others stumbling across this question looking for a more generic bounding solution.

    double boundBetween(double val, double lowerBound, double upperBound){
       if(lowerBound > upperBound){std::swap(lowerBound, upperBound);}
       val-=lowerBound; //adjust to 0
       double rangeSize = upperBound - lowerBound;
       if(rangeSize == 0){return upperBound;} //avoid dividing by 0
       return val - (rangeSize * std::floor(val/rangeSize)) + lowerBound;
    }
    

    A related question for integers is available here: Clean, efficient algorithm for wrapping integers in C++

提交回复
热议问题