Last active
May 13, 2020 17:12
-
-
Save mbitsnbites/b820f94ecceb4dc6de8a98b0e94a5eb9 to your computer and use it in GitHub Desktop.
Tailor series approximation of sin(x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float fast_sin(float x) { | |
// 1) Reduce periods of sin(x) to the range -PI/2 to PI/2. | |
const int period = (int)(x * (1.0f / 3.141592654f) + 0.5f); | |
const int negate = period & 1; | |
x -= 3.141592654f * ((float)period - 0.5f); | |
// 2) Use a Tailor series approximation in the range -PI/2 to PI/2. | |
// See: https://en.wikipedia.org/wiki/Taylor_series#Approximation_error_and_convergence | |
// sin(x) ≃ x - x³/3! + x⁵/5! - x⁷/7! | |
// Note: 3! = 6, 5! = 120, 7! = 5040 | |
const float x2 = x * x; | |
const float x3 = x2 * x; | |
const float x5 = x3 * x2; | |
const float x7 = x5 * x2; | |
float y = x - (1.0f/6.0f) * x3 + (1.0f/120.0f) * x5 - (1.0f/5040.0f) * x7; | |
return negate ? -y : y; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment