Tuesday, August 31, 2010

Solving Quadratic Equations in AS3

ActionScript 3 provides a convenient way to solve quadratic equations. To refresh your memory, a quadratic equation takes this form:

a*x^2 + b*x+c = 0

Where a, b, and c are constants.

Solutions of a quadratic equation (its roots) may be real or imaginary. When getting the roots in ActionScript only real roots are considered. So, there can be 1, 2, or no roots found.

Here's how you use it:

import fl.motion.*
var results:Array = BezierSegment.getQuadraticRoots(a, b, c);

I ran some speed tests of the above against solving it manually. The built-in way is about 40% faster. Here is how I tested it. I ran each way 1,000,000 times. I think its pretty amazing that we can do this 2,000,000 times in like 3 seconds.



function getQuadraticRoots(a:Number, b:Number, c:Number):Array {
var r! esults:Array = new Array();
var sqt:Number = Math.sqrt(Math.pow(b, 2) - 4*a*c);
var root1:Number = (b+sqt)/(2*a);
var root2:Number = (b-sqt)/(2*a);
if (!isNaN(root1)) {
results.push(root1);
}
if (!isNaN(root2)) {
results.push(root2);
}
return results;
}
function testCustomFunction() {
var startTime:Number = new Date().getTime();
for (var i:int=0;i<1000000;++i) {
var results:Array = getQuadraticRoots(100*Math.random(), 100*Math.random(), 100*Math.random());
}
var endTime:Number = new Date().getTime();
trace("Custom time: "+(endTime-startTime));
}
testCustomFunction();

import fl.motion.*;
function testBuiltInFunction() {
var startTime:Number = new Date().getTime();
for (var i:int=0;i<1000000;++i) {
var results:Array = BezierSegment.getQuadraticRoots(100*Math.random(), 100*Math.random(), 100*Math.random());
}
var! endTime:Number = new Date().getTime();
trace("Built-in ! time: "+ (endTime-startTime));
}
testBuiltInFunction();

solve quadratic

No comments:

Post a Comment