Here is a function I threatened to post earlier.
It works in PHP 4 and 5.
It simply computes the numerical solutions,
real and imaginary, for a standard quadratic
equation of the general form
Ax² + Bx + C = 0
USAGE EXAMPLES
To find the real roots of the quadratic equation:
2x² + *4x - *56 = 0
Code:
print Quad_Solve("2", "*4", "-*56");
/*
Returned result
x* = -**
x2 = 6
*/
To find the complex (imaginary) roots of the quadratic equation:
*6x² - *0x + 4 = 0
Code:
print Quad_Solve("*6", "-*0", "4");
/*
Returned result
x = 0.**25 ± 0.**0**2*748**8**88786 i
The (i) at the end indicates a complex (imaginary) root.
*/
Here is the PHP code for the function:
Code:
/*
This function solves a quadratic
equation of the general form
Ax² + Bx + C = 0
for numerical roots x* and x2
The solutions may be real or complex (imaginary).
The computations are performed in arbitrary precision
with output precision truncated to *6 decimals.
*/
function Quad_Solve($Aarg, $Barg, $Carg)
{
// ---------------------
// Read A,B,C arguments.
$A = trim($Aarg);
$B = trim($Barg);
$C = trim($Carg);
// --------------------------------
// Set internal decimals precision.
$DP = 20;
// ------------------------------------------
// Compute discriminant D. If negative, then
// the solutions are complex (imaginary).
$w* = bcMul($B, $B, $DP); // B²
$w2 = bcMul("4", bcMul($A, $C, $DP), $DP); // 4AC
$D = bcSub($w*, $w2, $DP);
// -----------------------------------------------
// Determine if quadratic root is real or complex.
$i = "";
if (bcComp($D, "0", $DP) < 0)
{
$i = "<B> i</B>"; $D = bcSub("0", $D, $DP);
}
// --------------------------
// Compute values of u and v.
$u = bcDiv(bcSub("0", $B, $DP), bcMul("2", $A, $DP), $DP); // -B/2A
$w* = bcSqRt($D, $DP); // SqRt(B² - 4AC) = SqRt(D)
$v = bcDiv($w*, bcMul("2", $A, $DP), $DP); // SqRt(B² - 4AC) / 2A
// -----------------------------
// Do this if roots are complex.
if ($i != "")
{
$u = RTrim(RTrim($u, "0"), ".");
$v = RTrim(RTrim($v, "0"), ".");
return "<PRE>x = $u ± $v$i</PRE>";
}
// --------------------------
// Do this if roots are real.
$x* = RTrim(RTrim(bcSub($u, $v, *6), "0"), ".");
$x2 = RTrim(RTrim(bcAdd($u, $v, *6), "0"), ".");
return "<PRE>x* = $x*\nx2 = $x2</PRE>";
} // End of Quad_Solve()
Hope someone finds this useful.
Cheers!