| 1 |
<?php |
| 2 |
/** |
| 3 |
* Copyright (C) 2023 Graham Breach |
| 4 |
* |
| 5 |
* This program is free software: you can redistribute it and/or modify |
| 6 |
* it under the terms of the GNU Lesser General Public License as published by |
| 7 |
* the Free Software Foundation, either version 3 of the License, or |
| 8 |
* (at your option) any later version. |
| 9 |
* |
| 10 |
* This program is distributed in the hope that it will be useful, |
| 11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
* GNU Lesser General Public License for more details. |
| 14 |
* |
| 15 |
* You should have received a copy of the GNU Lesser General Public License |
| 16 |
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
*/ |
| 18 |
/** |
| 19 |
* For more information, please contact <graham@goat1000.com> |
| 20 |
*/ |
| 21 |
|
| 22 |
namespace Goat1000\SVGGraph; |
| 23 |
|
| 24 |
/** |
| 25 |
* Class for algebraic functions |
| 26 |
*/ |
| 27 |
class Algebraic { |
| 28 |
|
| 29 |
private $type = 'straight'; |
| 30 |
private $coeffs = [0, 1]; |
| 31 |
|
| 32 |
public function __construct($type) |
| 33 |
{ |
| 34 |
$this->type = $type; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Sets the coefficients in order, lowest power first |
| 39 |
*/ |
| 40 |
public function setCoefficients(array $coefficients) |
| 41 |
{ |
| 42 |
$this->coeffs = $coefficients; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Returns the y value for a + bx + cx^2 ... |
| 47 |
*/ |
| 48 |
public function __invoke($x) |
| 49 |
{ |
| 50 |
$val = 0; |
| 51 |
foreach($this->coeffs as $p => $c) { |
| 52 |
switch($p) { |
| 53 |
case 0: $val = bcadd($val, $c); |
| 54 |
break; |
| 55 |
case 1: $val = bcadd($val, bcmul($c, $x)); |
| 56 |
break; |
| 57 |
default: |
| 58 |
$val = bcadd($val, bcmul($c, bcpow($x, $p))); |
| 59 |
break; |
| 60 |
} |
| 61 |
} |
| 62 |
return $val; |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* Creates a row of the vandermonde matrix |
| 67 |
*/ |
| 68 |
public function vandermonde($x) |
| 69 |
{ |
| 70 |
$t = $this->type; |
| 71 |
return $this->{$t}($x); |
| 72 |
} |
| 73 |
|
| 74 |
private function straight($x) |
| 75 |
{ |
| 76 |
return [$x]; |
| 77 |
} |
| 78 |
|
| 79 |
private function quadratic($x) |
| 80 |
{ |
| 81 |
return [$x, bcmul($x, $x)]; |
| 82 |
} |
| 83 |
|
| 84 |
private function cubic($x) |
| 85 |
{ |
| 86 |
$res = [$x, bcmul($x, $x)]; |
| 87 |
$res[] = bcmul($res[1], $x); |
| 88 |
return $res; |
| 89 |
} |
| 90 |
|
| 91 |
private function quartic($x) |
| 92 |
{ |
| 93 |
$res = $this->cubic($x); |
| 94 |
$res[] = bcmul($res[1], $res[1]); |
| 95 |
return $res; |
| 96 |
} |
| 97 |
|
| 98 |
private function quintic($x) |
| 99 |
{ |
| 100 |
$res = $this->cubic($x); |
| 101 |
$res[] = bcmul($res[1], $res[1]); |
| 102 |
$res[] = bcmul($res[1], $res[2]); |
| 103 |
return $res; |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
|