June
18th 2008
Solve quadratic equations with php

Posted under PHP & Programming

Ever wanted to solve quadratic equations with php? When I started to learn php, I wanted to see if I could make a script that solved quadratic equations. In a course I participated in, we made a MATLAB-script that did just that. A quadratic equation is on the form aX2+bX+c=0, and the solutions can be found with the quadratic formula:
Quadratic formula to solve quadratic equations

I have some problems with the formatting this article, I would appreciate any help.

To solve a quadratic equation with php, you need an input, and then the script produces the output. You can get input through a simple form, something like this:


<form action="/files/solvequadratic.php" method="post">
a:
<input type="text" name="a" size="15" maxlength="14" />
b:
<input type="text" name="b" size="15" maxlength="14" />
c:
<input type="text" name="c" size="15" maxlength="14" />
<input type="submit" value="Solve!" />
<input type="reset" value="Reset!" />
</form>

which turns into to this:

a: b: c:

What happens here, is that you enter three variables, a, b and c. These are stored as a, b and c. The form then sends the variables to the script solvequadratic.php located in the folder files for processing. So what is in solvequadratic.php?

<?php
$a = $_POST["a"];
$b = $_POST["b"];
$c = $_POST["c"];
$d = pow($b,2) - 4*$a*$c;
echo "You entered a = $a, b = $b, and c = $c. 

&#8220;;
if ($d < 0)
	{
	echo "The equation has no real solutions.";
	}
elseif ($a == 0)
	{
	echo "That is not a quadratic equation.";
	}
elseif ($d == 0)
	{
	echo "The equation has one solution. &#8220;;
	$x = ((-$b)+sqrt($d))/(2*$a);
	echo &#8220;X = $x&#8221;;
	}
else
	{
	echo &#8220;The equation has two solutions. &#8220;;
	$x1 = ((-$b) + sqrt($d)) / (2*$a);
	$x2 = ((-$b) - sqrt($d)) / (2*$a);
	echo &#8220;X1 = $x1 &#8220;;
	echo &#8220;X2 = $x2&#8243;;
	}
?>

For some reason, wordpress won’t let me use the

<xmp> tag as I want, so if the code above looks somewhat strange somewhere, that is the reason. &#8220; should show up as ” but it just won’t happen. Also, the </br> tag won’t show in the code. I’m trying to resolve this, but haven’t figured it out yet. I would appreciate any help. Here are the correct code as a .txt-file.

Anyway, if you are somewhat familiar with php, you should see what happens in the script. You are free to use this script for whatever you want, though I do doubt there is a need for this. However it is a good exercise to get to know php better, if you’re a beginner, like myself. As you might have noticed, you can try the script by using the form above. And yeah, I know the output page look like shit, but I’m to laze to do anything about it. This script can be expanded to solve quadratic equations with complex solutions as well, but I haven’t done that yet.

Trackback URI | Comments RSS

Leave a Reply