Thought I'd post this here, seeing as it's pretty cool, and fairly simple. Made it on a whim after a friend mentioned that one of the second year assignments (little practice one) is making a quad solver in C, so I had a go at it in PHP, on the spot. Took about 10minutes to write the first iteration, which was improved over the rest of today at random points to add extra functionality, such as a linear equation solver and the "filthy engineer" option. As it turns out, this is ar more functional than the second year assignment, which only requires it to solve quadratics with real roots using a command line input.
This simple PHP script can solve any quadratic (or linear - just enter 0 for x^2) equation, including solutions with non-real roots. It even accounts or those ilthy engineers and their wacky use of j to represent
imaginary numbers!
Only thing it doesn't do is reselect the correct radio button. I can think how to do this, but it's a bit messy and kinda pointless.
In total, there are 39 lines of code (I write fairly spread out, though) weighing in at just under 1KB. I am aware I use a lot of IF functions, but it does the job and is pretty clean.
Feel free to post up any versions you might have written, in any language (though preferably PHP). I'd be interested to see how other people do it differently. Adding formatting and header stuff to my code doesn't count
Click here for win.
Code:
<?php
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$letter = $_POST['letter'];
?>
<form method="post" action="quadsolver.php">
<input type="text" name="a" size="2" value="<?php echo "$a"; ?>" />x^2+
<input type="text" name="b" size="2" value="<?php echo "$b"; ?>" />x+
<input type="text" name="c" size="2" value="<?php echo "$c"; ?>" />=0
<input type="submit" value="Solve" /></br>
I am: <input type="radio" name="letter" value="i" checked />An awesome physicist. <input type="radio" name="letter" value="j" />A filthy engineer.</form>
<?php
$root = pow($b,2)-(4*$a*$c);
IF($a == 0)
{
$x = -$c/$b;
echo "Solution: x = $x";
}
ELSE
{
IF($root >= 0)
{
$x1 = (-$b+sqrt($root))/(2*$a);
$x2 = (-$b-sqrt($root))/(2*$a);
echo "Solutions: x = $x1, $x2";
}
ELSE
{
$img = sqrt(-$root)/(2*$a);
$real = -$b/(2*$a);
echo "Solutions: x = $real+$img $letter, $real-$img $letter";
}
}
?>
EDIT: Just realised I could probably tidy it up with an ELSEIF rather than the ELSE { IF, but that's not too big.