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:
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.
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.