public function testSolveSomeMore()
{
// f(x) = x³ - x - 2
// Find the root 1.521
// Example from https://en.wikipedia.org/wiki/Bisection_method
$func = function ($x) {
return $x ** 3 - $x - 2;
};
$tol = 0.001;
// Solve for f(x) = 0 where x is about 1.521
$a = 1;
$b = 2;
$expected = 1.521;
$x = BisectionMethod::solve($func, $a, $b, $tol);
$this->assertEquals($expected, $x, '', $tol);
// f(x) = x² - 3
// Find the root 1.7344
// Example from https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/10RootFinding/bisection/examples.html
$func = function ($x) {
return $x ** 2 - 3;
};
$tol = 0.01;
// Solve for f(x) = 0 where x is about 1.7344
$a = 1;
$b = 2;
$expected = 1.7344;
$x = BisectionMethod::solve($func, $a, $b, $tol);
$this->assertEquals($expected, $x, '', $tol);
// f(x) = e⁻ˣ (3.2sin(x) - 0.5cos(x))
// Find the root 3.2968
// Example from https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/10RootFinding/bisection/examples.html
$func = function ($x) {
return exp(-$x) * (3.2 * sin($x) - 0.5 * cos($x));
};
$tol = 0.0001;
// Solve for f(x) = 0 where x is about 3.2968
$a = 3;
$b = 4;
$expected = 3.2968;
$x = BisectionMethod::solve($func, $a, $b, $tol);
$this->assertEquals($expected, $x, '', $tol);
}