Gamajo Quadratic Equation Solver
PHP classes for working with, and solving, quadratic equations., (*1)
What Is A Quadratic Equation?
A quadratic equation is a univariate polynomial with degree of 2, that is then set to equal zero so that the indeterminate can be determined:, (*2)
ax2 + bx + c = 0, (*3)
Equations can often be solved with factoring or completing the square, but there is also a Quadratic Formula:, (*4)
, (*5)
The QuadraticEquation interface constructor accepts values for a, b and c and the Solver can return one or both roots, including imaginary roots., (*6)
Installation
composer require gamajo/quadratic --save
Requires PHP 7., (*7)
Usage
Basic Usage
Create an equation object, pass that to the solver, solve, and retrieve the roots:, (*8)
use Gamajo\Quadratic;
// Represents x^2 + 5x + 6 = 0.
$equation = new BasicQuadraticEquation(1, 5, 6);
$solver = new Solver($equation);
$solver->solve();
echo $solver->get(); // '2 and 3'
echo $solver->get('root1'); // '2'
echo $solver->get('root2'); // '3'
The Solver has no problem with complex roots:, (*9)
use Gamajo\Quadratic;
// Represents 3x^2 + 4x + 5 = 0.
$equation = new BasicQuadraticEquation(3, 4, 5);
$solver = new Solver($equation);
$solver->solve();
echo $solver->get(); // '-0.667 + 1.106i and -0.667 - 1.106i'
BasicQuadraticEquation Methods
The BasicQuadraticEquation class implements the QuadraticEquation interface, which in turn extends the Equation interface. As such, it supports the following methods:, (*10)
use Gamajo\Quadratic;
// Represents x^2 + 5x + 6 = 0.
$equation = new BasicQuadraticEquation(1, 5, 6);
echo $equation->getA(); // 1
echo $equation->getB(); // 5
echo $equation->getC(); // 6
print_r( $equation->getArgsAsArray() ); // [1, 5, 6]
There is also a hasValidArguments() method, but as this library uses scalar type declarations, the manual check to see if they are all integers is somewhat redundant., (*11)
Solver Methods
The Solver class can optionally set the maximum decimal place precision of the roots:, (*12)
use Gamajo\Quadratic;
// Represents 8x^2 + 5x - 2 = 0.
$equation = new BasicQuadraticEquation(8, 5, -2);
$solver = new Solver($equation);
$solve->setPrecision(4); // Default precision is 3
echo $solve->getPrecision(); // 4
$solver->solve();
echo $solver->get(); // '-0.9021 and 0.2771' instead of '-0.902 and 0.277'
Change Log
See the change log., (*13)
License
MIT., (*14)
Contributions
Contributions are welcome - fork, fix and send pull requests against the develop branch please., (*15)
Credits
Built by Gary Jones.
Original procedural code version, copyright 2004 Gary Jones.
This version copyright 2016 Gamajo Tech, (*16)