Fastest implementation of sine, cosine and square root in C++ (doesn't need to be much accurate)

前端 未结 15 2007
执笔经年
执笔经年 2020-12-04 10:55

I am googling the question for past hour, but there are only points to Taylor Series or some sample code that is either too slow or does not compile at all. Well, most answe

15条回答
  •  感情败类
    2020-12-04 11:45

    An approximation for the sine function that preserves the derivatives at multiples of 90 degrees is given by this formula. The derivation is similar to Bhaskara I's sine approximation formula, but the constraints are to set the values and derivatives at 0, 90, and 180 degrees to that of the sine function. You can use this if you need the function to be smooth everywhere.

    #define PI 3.141592653589793
    
    double fast_sin(double x) {
        x /= 2 * PI;
        x -= (int) x;
    
        if (x <= 0.5) {
            double t = 2 * x * (2 * x - 1);
            return (PI * t) / ((PI - 4) * t - 1);
        }
        else {
            double t = 2 * (1 - x) * (1 - 2 * x);
            return -(PI * t) / ((PI - 4) * t - 1);
        }
    }
    
    double fast_cos(double x) {
        return fast_sin(x + 0.5 * PI);
    }
    

    As for its speed, it at least outperforms the std::sin() function by an average of 0.3 microseconds per call. And the maximum absolute error is 0.0051.

提交回复
热议问题