rizalmf / deductive-formula
评估给定的数学表达式
0.0.1-alpha
2021-04-04 13:28 UTC
Requires
- php: >=7.0
- ext-mbstring: *
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-06 10:01:24 UTC
README
DeductiveFormula 是从给定字符串中评估变量表达式的库
通过 "composer require" 安装
composer require rizalmf/deductive-formula
用法
use rizalmf\formula\DeductiveFormula; use rizalmf\formula\exception\FormulaException; require_once __DIR__ . '/vendor/autoload.php'; // example path $formula = new DeductiveFormula();
示例 1: (定义表达式 & 设置公式)
try { $expression = '{foo}^({bar}/2+(2+3^(1/2)))'; $requestedVariables = $formula->setFormula($expression); var_dump($formula->getFormula()); var_dump($requestedVariables); } catch (FormulaException $e) { // handle Exceptions } // output : // {foo}^({bar}/2+(2+3^(1/2))) // array ([0] => "foo", [1] => "bar")
示例 2: (设置变量)
// ... // 1. define value per variable $formula->setVariable("foo", 4); $formula->setVariable("bar", 1); // 2. use array $formula->setVariables([ "foo" => 4, "bar" => 1 ]);
示例 3: (获取变量)
// ... // 1. get value from specific variable var_dump($formula->getVariable("foo")); // output : 4 // 2. get values all variables var_dump($formula->getVariables()); // output : array ([foo] => 4, [bar] => 1) // 1. get possible variables from Formula var_dump($formula->getRequestedVariables()); // output : array ([0] => "foo", [1] => "bar")
示例 4: (评估)
$result = $formula->execute(); var_dump($result); // output : 353.141268350837
示例 5: (设置迭代限制 & 调试)
// (optional) set limit iteration calculating machine. default 200 $formula->setLimit(50); // show prepared formula var_dump($formula->getFormulaExposed()); // output : 4^(1/2+(2+3^(1/2))) // debug $result = $formula->execute(true); var_dump($result); // output : // iteration-1 => 4^(1/2+(2+3^(1/2))) // iteration-2 => 4^(1/2+(2+3^0.50)) // iteration-3 => 4^(1/2+(2+1.73205080756888)) // iteration-4 => 4^(1/2+3.73205080756888) // iteration-5 => 4^(0.50+3.73205080756888) // iteration-6 => 4^4.23205080756888 // 353.141268350837
异常树
FormulaException |- BadFormulaException
单元测试
- Composer 是运行测试的前提条件。
composer install
- 可以从根目录运行此命令来执行测试
./vendor/bin/phpunit test
许可证
MIT 许可证(MIT)版权所有 (c) 2021 Rizal Maulana Fahmi