Solving Quadratics

I was kinda bored today and as I didn’t want to do my maths homework. My friend, who was on-task was trying to use MSN Search to solve a quadratic and complained it didn’t provide both solutions so I decided to write a little script to solve quadratic equations. Now this isn’t hard at all; it simply involves taking 4 inputs and using the quadratic formula:

Quadratic Formula 

So I wrote my little calculator using Javascript and turned up the font size to make it a little bit more "Web 2.0". I also added a little check which works out the discriminant value of the quadratic equation to determine whether it can actually be solved before solving. In all it took about 10 minutes; the main difficulty was working out the Javascript function to do powers.

Taking Plain Text 

Then I thought back to yesterday where I read a series of articles on Sitepoint about regular expressions which explained it all pretty well. I thought I’d put some of it into practice and create an improved version which allows the user to type in an equation and have the script automatically work out all the terms.

What it does is to take the inputted equation and split it in half on the = character. This gives two terms – one which is assumed to be a constant and one which is assumed to be the actual quadratic meat. This side is then split into it’s individual terms using the characters + and -. A regexp is then run on each term to determine it’s power, and it adds it all up. It took a while to get it to all work and it seems to work pretty well.

Here’s the improved version which takes a plain text input and works out the quadratic equation. It works well in Firefox and Opera. It’s about 70 lines in all and although I could have probably done it in quite a bit less, it works well.

Messenger Script

Now, I was getting really carried away so I decided to write a script which would allow my contacts on MSN Messenger to send me a quadratic equation and my computer would work it out and respond. In fact, the amount of times people ask me to help them solve quadratics is shocking so this could have saved a load of time.

This is mainly a copy and paste of the Javascript from the browser based calculator with a few modifications and hooks to make it work with Windows Live Messenger and Messenger Plus Live.

Get the script here

All in all, nothing particularly revolutionary or exciting, but an afternoon spent where I practised my Javascript, regular expressions and maths all in one. 

4 thoughts on “Solving Quadratics

  1. This is pretty cool

    I wonder if it would be even possible to have Javascript handle solutions involving the imaginary unit i

Leave a Reply

Your email address will not be published. Required fields are marked *