PHP Classes

File: example.quadraticequation.php

Recommend this page to a friend!
  Classes of Alexandre Cisneiros   Quadratic Equation Solver   example.quadraticequation.php   Download  
File: example.quadraticequation.php
Role: Example script
Content type: text/plain
Description: An usage example
Class: Quadratic Equation Solver
Get the roots of a quadratic equation
Author: By
Last change: Typo correction.
Date: 12 years ago
Size: 2,213 bytes
 

Contents

Class file image Download
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quadratic Equations Example</title>
</head>

<body>
<h1>Let's do some math!</h1>
<p>
<?php
include ('class.quadraticequation.php');

// Inline generation: 3x^2 - 4x + 2 = 0 (default precision = 2)
print ('Inline generation with default precision (2): <br />3x^2 - 4x + 2 = 0 (roots: ' . new QuadraticEquation(3, -4, 2) . ')');
print (
'<br /> <br />');

// Step-by-step generation: 4x^2 + 2x - 10 = 0 (precision = 3)
$eq = new QuadraticEquation;
$eq->setA(4);
$eq->setB(2);
$eq->setC(-10);
$eq->setPrecision(3);
print (
'Step-by-step generation with precision = 3: <br />4x^2 + 2x - 10 = 0 (roots: ');
foreach (
$eq->getRoots() as $root) // Please do a try/catch as done below. This is only an example!
{
    print (
$root . ';');
}
print (
')<br /> <br />');

// It is always a good practice to check for errors!
// Error checking: 4x^2 + -4x + 100 = 0 (default precision = 2)
$eq = new QuadraticEquation(4, -4, 100);
print (
'Error checking: <br />4x^2 + -4x + 100 = 0 (roots: ');
try
{
    foreach (
$eq->getRoots() as $root)
    {
        print (
$root . ';');
    }
}
catch (
Exception $e)
{
    print (
$e->getMessage());
}
print (
')<br /> <br />');

// You don't have to create another instance of the object to solve another equation,
// if you don't want to. You can just set new values and getRoots() once more. I'll use the
// same $eq instance we just made, change the values and solve another equation.
$eq->setC(0);
$eq->setPrecision(4);
print (
'Using the same object with new values (precision = 4): <br />4x^2 + 2x = 0 (roots: ');
try
{
    foreach (
$eq->getRoots() as $root)
    {
        print (
$root . ';');
    }
}
catch (
Exception $e)
{
    print (
$e->getMessage());
}
print (
')<br /> <br />');
?>
</p>
<hr />
<p>Thanks for using my class! I'd like to know if you use it, so please notify me on <strong>alexandre [at] cisneiros.com</strong>! ;-)<br />
Alexandre Cisneiros Filho - http://cisneiros.com</p>
</body>
</html>