Hi.

Just been looking at some cool optimization on osflash.org, and saw a post that says about creating a faster method than the internal "Math.sqrt" routine using AS3.

http://osflash.org/as3_speed_optimizations

But, I did my own tests to see I could confirm their results, and well, my tests disagreed with their conclusions - (ie mine showed that the "Math.sqrt" function is fastest). Anyone confirm their results? and accuracy?

But if anyone wants to test what I got, then here is my code.. And if anyone has an ultrafast square root hack, then please let me know!!

Regards,

Dean

on my machine outputs following results...Code:// Math.sqrt vs Babylonian speed test function Sqrt2( X:Number ):Number { var b:Number = X * 0.25, a:Number, c:Number; do { c = X / b; b = (b + c) * 0.5; a = b - c; if (a < 0) a = -a; } while (a > 0.01); return b; } function Sqrt3( X:Number ):Number { var b:Number = X * 0.25; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; b = (b + (X / b)) * 0.5; return b; } var t0:uint, t1:uint, t2:uint, t3:uint, t4:uint; var n:int; var r:Number; var s:Number; // test calculation trace("test calculations"); for( n=0;n<10;n++){ r = Math.random() * 1000000; trace( "Math.sqrt = "+Math.sqrt(r) ); trace( "Sqrt2 = "+Sqrt2(r) ); trace( "Sqrt3 = "+Sqrt3(r) ); trace(" "); } t0 = getTimer(); for(n=0; n<1000000; n++){ r = Math.random(); // s = ... } t0 = getTimer() - t0; t1 = getTimer(); for(n=0; n<1000000; n++){ r = Math.random(); s = Math.sqrt( r ); } t1 = getTimer() - t1; t2 = getTimer(); for(n=0; n<1000000; n++){ r = Math.random(); s = Sqrt2( r ); } t2 = getTimer() - t2; t3 = getTimer(); for(n=0; n<1000000; n++){ r = Math.random(); s = Sqrt3( r ); } t3 = getTimer() - t3; t4 = getTimer(); for(n=0; n<1000000; n++){ r = Math.random(); s = r * 0.25; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; s = (s + (r / s)) * 0.5; } t4 = getTimer() - t4; trace(" "); trace("results"); trace("empty test = "+t0+" ms"); trace("Math.sqrt test = "+t1+" ms subtracted from empty test = "+(t1-t0)); trace("Sqrt2 test = "+t2+" ms subtracted from empty test = "+(t2-t0)); trace("Sqrt3 test = "+t3+" ms subtracted from empty test = "+(t3-t0)); trace("no function test = "+t4+" ms subtracted from empty test = "+(t4-t0)); trace(" ");

...so, the Math.sqrt is fastest, followed by the unravelled Babylonian test.Code:empty test = 139 ms Math.sqrt test = 232 ms subtracted from empty test = 93 Sqrt2 test = 431 ms subtracted from empty test = 292 Sqrt3 test = 401 ms subtracted from empty test = 262 no function test = 346 ms subtracted from empty test = 207

Anyway. Thought it might be interesting to put here.