 ### May contain nuts.

In the recent theme of speed testing I thought I'd better double check my atan2 results, and comparing the below method to the built in one I got the following:

runAtan2():  2161
runAtan2Quicker():  1159

( For more about how I test this stuff, please check this recent post )

Phew, something actually working quickly as it's meant to.

The following method is based on code by Jim Shima, http://dspguru.com/comp.dsp/tricks/alg/fxdatan2.htm

private static var coeff_1:Number = Math.PI / 4;
private static var coeff_2:Number;
private static var r:Number;
private static var angle:Number;
private static var absY:Number;

//--------------------------------------------------------------------------
public static function atan2(y:Number,x:Number):Number{
coeff_2 = 3 * coeff_1;
absY=y;
if (absY < 0) absY = -absY;                    //Math.abs
if(x>=0){
r= (x - absY) / (x + absY);
angle = coeff_1 - coeff_1 * r;
} else {
r = (x + absY) / (absY - x);
angle = coeff_2 - coeff_1 * r;
}
return y < 0 ? -angle : angle;
}

I've used static properties / method 'cause it's part of my MathX class ( So if you're going to set up a similar way, create a class called MathX and then the usage would be,

var value:Number=MathX.atan2(y,x);

Exactly the same as the built in method ).

Squize.

• #### tonypa

8/28/2008 7:42:50 PM |

I am sure you know, but the results compared to built-in Math.atan2 are different. Dont you think loss in accuracy may cause problems?

• #### Squize

8/29/2008 11:40:43 AM |

It depends on what you're using it for. If it's just for say rotating a missile towards a baddie then there's no harm done, if you were building a physics engine using it then yeah I'd use the more accurate built in one.

A lot of speed ups come at the cost of accuracy, but for the majority of games it's not an issue.

• #### jeep

10/24/2008 11:47:48 PM |

Hmm, I tested the speeds and found it to be slower than Math.atan2

• #### Squize

10/26/2008 1:22:20 PM |

Could you show me what you used to test it please ? Cheers