Skip to content

Instantly share code, notes, and snippets.

@geraldyeo
Created May 24, 2011 03:52
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save geraldyeo/988116 to your computer and use it in GitHub Desktop.
Save geraldyeo/988116 to your computer and use it in GitHub Desktop.
Fast and accurate sine/cosine approximation
//1.27323954 = 4/pi
//0.405284735 =-4/(pi^2)
/*********************************************************
* low precision sine/cosine
*********************************************************/
//always wrap input angle to -PI..PI
if (x < -3.14159265)
x += 6.28318531;
else
if (x > 3.14159265)
x -= 6.28318531;
//compute sine
if (x < 0)
sin = 1.27323954 * x + .405284735 * x * x;
else
sin = 1.27323954 * x - 0.405284735 * x * x;
//compute cosine: sin(x + PI/2) = cos(x)
x += 1.57079632;
if (x > 3.14159265)
x -= 6.28318531;
if (x < 0)
cos = 1.27323954 * x + 0.405284735 * x * x
else
cos = 1.27323954 * x - 0.405284735 * x * x;
}
/*********************************************************
* high precision sine/cosine
*********************************************************/
//always wrap input angle to -PI..PI
if (x < -3.14159265)
x += 6.28318531;
else
if (x > 3.14159265)
x -= 6.28318531;
//compute sine
if (x < 0)
{
sin = 1.27323954 * x + .405284735 * x * x;
if (sin < 0)
sin = .225 * (sin *-sin - sin) + sin;
else
sin = .225 * (sin * sin - sin) + sin;
}
else
{
sin = 1.27323954 * x - 0.405284735 * x * x;
if (sin < 0)
sin = .225 * (sin *-sin - sin) + sin;
else
sin = .225 * (sin * sin - sin) + sin;
}
//compute cosine: sin(x + PI/2) = cos(x)
x += 1.57079632;
if (x > 3.14159265)
x -= 6.28318531;
if (x < 0)
{
cos = 1.27323954 * x + 0.405284735 * x * x
if (cos < 0)
cos = .225 * (cos *-cos - cos) + cos;
else
cos = .225 * (cos * cos - cos) + cos;
}
else
{
cos = 1.27323954 * x - 0.405284735 * x * x;
if (cos < 0)
cos = .225 * (cos *-cos - cos) + cos;
else
cos = .225 * (cos * cos - cos) + cos;
}
@nikhilsinha
Copy link

Do you have any snippets for arctan, arccos, or arcsin?

@q2p
Copy link

q2p commented Jan 17, 2020

Too many branches. So it's not very fast or accurate.

@terryspitz
Copy link

Simplified cosine fn (in F#):

let fastCos x =
let mutable x = x / 3.14159265 + 1.5
let xx = 2. * floor (x / 2.)
x <- x - xx - 1.
assert (-1.<=x && x<1.)
if x < 0. then
4. * (1.+x) * x
else
4. * (1.-x) * x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment