## Solving Quadratic Equations in AS3

June 5, 2007 by jobemakar

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 results: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();

### Like this:

Like Loading...

*Related*

on June 5, 2007 at 8:37 am |BinaryMoonHi JobeJust a quick note to let you know that I am finding your blog very useful – please keep it up (and post lots more fla’s 🙂 )On the Quadratic thing… whilst it’s interesting I can’t think of any situation in which I’d want to use Quadratic equations in a game. Do you have any examples of uses?

on June 5, 2007 at 10:57 am |Jobe MakarHi,I’m glad you find my posts helpful!The need to solve a quadratic equation doesn’t come up all the time. So you won’t find it useful frequently. But it does come up. Here is a common example – an equation of motion that includes gravity.y(t) = y_i + v_y*t + 1/2*a*t^2You know the object’s current position and velocity. Acceleration (a) could be gravity. You want to know how long it will take for the object to reach a sepcific position (say the ground).Just plug in your initial values and then use the technique described here to find the roots (the times).In this particular example ( a ball falling under gravity) you could easily have 2 correct answers under the right conditions. Lets say the ball is on the ground, so initial y = 0, and is shot up into the air vertically, initial v_y > 0, and acceleration is gravity. You want to know how long it will take to hit the ground.You’ll come up with two times, 0 and something non-zero. 0 is valid because it is on the ground at t=0, the start time. And then eventually it will come back down.

on June 7, 2007 at 10:59 am |Binary MoonOk – I guess that makes sense 🙂 I’ve not developed any games that would require those sorts of calculations, hence my confusion, but I can see how this sort of thing would be helpful in some situationsCheers

on June 7, 2007 at 11:32 am |Jobe MakarHere are a couple more situations where it would come in handy. Notice that conceptually these have 2 answers:** Collision detection between spheres that take time into account** Determining the points where a line intersects a circle

on June 7, 2007 at 5:13 pm |Jacob CorreiaThats because your custom function is not optimized. The overhead of simply creating the array how you are is much of the cost.If you optimized your version you could get it to run as faster or even faster than calling it through the BezierSegment class.

on June 7, 2007 at 6:28 pm |Jobe MakarJacob,That’s a good point. I agree that my code could be optimized. But you can’t get around the fact that you need to return 2 pieces of information. You could pass in your own array and get it back out to cut out the creation expense. But then we’re not doing an apples to apples comparison between custom and built-in. My intention was to compare one black box to another.As a quick test I tried passing in an array and reusing it every time. The performance was increased but built-in was still much faster.

on July 19, 2007 at 4:55 am |jason zGreat post. I’m actually in a situation where I need to find the tangent lines to two circles, so it looks like I’ll be using the guidelines herehttp://www.cut-the-knot.org/Curriculum/Geometry/TangentTwoCirclesI.shtml(the long link wasn’t playing nice with formatting, so i broke it apart)And then using Flash’s quadratic equation to do some dirty work. Unless, of course, you know of a better way to get the job done…Again, thanks for the post!

on August 1, 2007 at 8:58 pm |Robert PennerHi Jobe, maybe the Math.pow() for the square is slowing your function down. When I wrote BezierSegment.getQuadraticRoots(), I basically ported it over from a C++ function in Flash Authoring, and didn’t spend any time trying to optimize it. Looking at it again, there are a few things I could have done to clean it up and possibly save a little time.

on August 7, 2007 at 4:30 am |Jobe MakarJason-z,To find the tangent line between two circles you need to find a few pieces of information. First, I’m assuming the circles are touching on an edge.- Find the point where they are touching. This is easy ifyou know where the circles are. (ask if you need more info)- Use these positions to find the angle of the line that connects the two centers.- Use the angle and any known position to find the intersection point.- With the intercectio point and the inverse of the slope of the line that connects the two circles, you now have the slope and 1 point on the tangential line.It doesn’t sound quite as easy when I write it out like that. I’m happy to fill in more blanks if needed. Good luck!

on August 7, 2007 at 4:33 am |Jobe MakarRobert,Thanks for the info! I appreciate tips from the guy who wrote some of the most useful classes!

on September 10, 2007 at 12:14 am |jasonjobe -thanks for the response about the tangent lines. actually, the two circles are arbitrarily positioned in the cartesian plane. i was stuck for a bit, but fortunately i work with someone who has his phd in physics and he pushed some equations into mathematica and let it do the heavy lifting to generate generic equations for the tangent lines. it was rather nice to see it all work.the point of all of this was to accurately draw what is essentially a 2-D comet: a circle with a trail. i figured the best way to do the trail was to make iteratively smaller copies of the original object and draw tangent lines between the copies. it worked out really well.i’ve been pulled onto other work so i haven’t been able to finish up the complete animation, but when i do, i’ll send along a url so you can check it out. thanks again!jason

on November 14, 2009 at 8:25 pm |AnonymousWho knows where to download XRumer 5.0 Palladium? Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

on March 28, 2010 at 3:29 pm |AnonymousHello, I am trying to create a particle system that involves using the Z property. Moving a missile from the rear to the front and landing into an explosion. I wanted to use a parabola to create this effect. I understand quadratics but am having trouble converting it into code.