Fast Sine and Cosine Approximation
- let t = 0, cos, sin, x, y; 
- const PI = Math.PI; 
- const TWO_PI = PI * 2; 
- const HALF_PI = PI / 2; 
- const tA = 4 / PI; 
- const tB = 4 / PI ** 2; 
- const canvas = document.body.appendChild(document.createElement('canvas')); 
- const c = canvas.getContext('2d'); 
- canvas.width = canvas.height = 300; 
- function loop() { 
- // low precision sine/cosine
- // always wrap input angle to -PI..PI
- t += 0.1; 
- if (t < -PI) { 
- t += TWO_PI; 
- } else if (t > PI) { 
- t -= TWO_PI; 
- }
- // compute sine
- if (t < 0) { 
- sin = tA * t + tB * t * t; 
- } else { 
- sin = tA * t - tB * t * t; 
- }
- // compute cosine: sin(t + PI/2) = cos(t)
- t += HALF_PI; 
- if (t > PI) { 
- t -= TWO_PI; 
- }
- if (t < 0) { 
- cos = tA * t + tB * t * t; 
- } else { 
- cos = tA * t - tB * t * t; 
- }
- t -= HALF_PI; // move the shape 
- x = 110 + 100 * cos; 
- y = 110 + 100 * sin; 
- c.fillStyle = 'rgba(100, 100, 20, .5)'; 
- c.fillRect(x, y, 10, 10); 
- window.requestAnimationFrame(loop); 
- }
- loop(); 
This is an old trick for fast sine/cosine approximation. I learned about it from Michael Baczynski’s blog which now seems to be down. Here is a wayback link for the original article and another one to a more in-depth discussion about it:
 
original post
 
original thread
It’s unlikely that the speed gain (if there even is one here) makes sense in javascript. This is really more for fun… a quick search will turn up all kinds of cool info about fast sine/cosine stuff.