Tag Archives: actionscrpt

Low Precision Sine and Cosine

Actionscript:
  1. var t:Number=0, cos:Number, sin:Number;
  2.  
  3. var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
  4. addChild(new Bitmap(canvas));
  5.  
  6. var shape:Shape = new Shape();
  7. with(shape.graphics) beginFill(0x568338, .2), drawCircle(0,0,10);
  8.  
  9. addEventListener(Event.ENTER_FRAME, onLoop);
  10. function onLoop(evt:Event):void {
  11.    
  12.          t += .1;
  13.         // -- low precision sine/cosine
  14.         //always wrap input angle to -PI..PI
  15.         if (t <-3.14159265){
  16.             t += 6.28318531;
  17.         }else{
  18.         if (t>  3.14159265)
  19.             t -= 6.28318531;
  20.         }
  21.        
  22.         //compute sine
  23.         if (t <0){
  24.             sin = 1.27323954 * t + .405284735 * t * t;
  25.         }else{
  26.             sin = 1.27323954 * t - 0.405284735 * t * t;
  27.         }
  28.        
  29.         //compute cosine: sin(t + PI/2) = cos(t)
  30.         t += 1.57079632;
  31.         if (t>  3.14159265){
  32.             t -= 6.28318531;
  33.         }
  34.        
  35.         if (t <0){
  36.             cos = 1.27323954 * t + 0.405284735 * t * t
  37.         }else{
  38.             cos = 1.27323954 * t - 0.405284735 * t * t;
  39.         }
  40.         t -= 1.57079632;
  41.        
  42.         // move the shape
  43.         shape.x = 200 + 100 * cos;
  44.         shape.y = 200 + 100 * sin;
  45.        
  46.         // draw to the canvas
  47.         canvas.draw(shape, shape.transform.matrix);
  48. }

This snippet draws a circle using low precision sine and cosine... you'll notice that its not a perfect looking circle:


Back in January I saw this blog post by Michael Baczynski over at http://lab.polygonal.de/. The blog post describes a technique for fast sine and cosine approximation - (I highly recommend giving it a read - very fun stuff).

It's worth noting that there is a higher precision sine and cosine that will likely draw a better looking circle but will be about half as fast. According to the original post ... the low precision technique is approximately 14x faster than using Math.cos()/Math.sin().

There some other really great posts over at polygonal go check them out.

Posted in Math, motion | Also tagged | 2 Comments