Last active
December 20, 2015 19:18
-
-
Save Jamil/6181900 to your computer and use it in GitHub Desktop.
Simple approximations for sine and cosine using recursive identities + small angle approximation and Maclaurin Series
This file contains hidden or 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
// Math Defs | |
float factorial (float n) { | |
if (n < 1) | |
return 1; | |
return (n*factorial(n-1)); | |
} | |
// Approximations Using Trig Identities & Small Angle Formulae | |
float approxSin (float angle) { | |
if (angle < 0.1) | |
return angle; // sin x = x | |
return 3*approxSin(angle/3) - 4*pow(approxSin(angle/3), 3); | |
} | |
float approxCos (float angle) { | |
if (angle < 0.1) | |
return 1 - (pow(angle, 2)/2); // cos x = 1 - 1/2 (x^2) | |
return 4*pow(approxCos(angle/3), 3) - 3*approxCos(angle/3); | |
} | |
// Approximations Using Maclaurin Series | |
float remainderTerm (float x, int n) { | |
return pow(x, n+1)/factorial(n+1); | |
} | |
float sineHelper (float x, int n) { | |
if (n && remainderTerm(x, n) < THRESHOLD) | |
return 0; | |
return ((n % 2 ? -1 : 1) * (pow(x, 2*n+1)/factorial(2*n+1)) + sineHelper(x, n+1)); | |
} | |
float sine (float x) { | |
int multiplier = x / (2*M_PI); | |
x -= (2*M_PI*multiplier); | |
return sineHelper(x, 0); | |
} | |
float cosHelper (float x, int n) { | |
if (n && remainderTerm(x, n) < THRESHOLD) | |
return 0; | |
return ((n % 2 ? -1 : 1) * (pow(x, 2*n)/factorial(2*n)) + cosHelper(x, n+1)); | |
} | |
float cosine (float x) { | |
int multiplier = x / (2*M_PI); | |
x -= (2*M_PI*multiplier); | |
return cosHelper(x, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment