sin, cos, tan and rounding error

前端 未结 9 636
执念已碎
执念已碎 2020-12-06 14:09

I\'m doing some trigonometry calculations in C/C++ and am running into problems with rounding errors. For example, on my Linux system:

#include 

        
9条回答
  •  天命终不由人
    2020-12-06 14:36

    Unless your program requires significant digits out to the 16th decimal place or more, you probably can do the rounding manually. From my experience programming games we always rounded our decimals to a tolerable significant digit. For example:

    #include 
    #include 
    #include 
    
    #define HALF 0.5
    #define GREATER_EQUAL_HALF(X) (X) >= HALF
    
    double const M_PI = 2 * acos(0.0);
    
    double round(double val, unsigned  places = 1) 
    {
        val = val * pow(10.0f, (float)places);
        long longval = (long)val;
        if ( GREATER_EQUAL_HALF(val - longval) ) {
           return ceil(val) / pow(10.0f, (float)places);
        } else {
          return floor(val) / pow(10.0f, (float)places);
        }
    }
    
    int main() 
    {
        printf("\nValue %lf", round(sin(M_PI), 10));
        return 0;
    }
    

提交回复
热议问题