sufir/php-calc
Composer 安装命令:
composer require sufir/php-calc
包简介
Simple calculation expressions
README 文档
README
Install
Via Composer
$ composer require sufir/php-calc
Usage
$lexer = new Lexer(); $converter = new Converter(); $calc = new Calc(20);
D&D d20 check example:
$calc->registerFunction('d20', function () { return rand(1, 20); }); $charAbilities = ['ability' => 15, /*... etc */]; $difficultyClass = 12; $checkExpr = 'd20() + ($ability / 2 – 5)'; $tokens = $lexer->parse($checkExpr); $result = $calc->evaluate( $converter->converToPostfix($tokens), $charAbilities ); // simple d20 ability check if ($result < $difficultyClass) { echo 'You fail!!!'; } else { echo 'Congratulation!'; }
Area of a circle example:
$expr = '$Pi*$r^2'; $radiusList = [5, 10, 15, 25, 50]; $calc->defineVar('$Pi', '3.14159265358979323846'); $tokens = $lexer->parse($expr); foreach ($radiusList as $radius) { echo 'Pi * ', $radius , '^2 = ', $calc->evaluate( $converter->converToPostfix($tokens), ['r' => $radius] ), "\n"; } /* Pi * 5^2 = 78.53981633974483096150 Pi * 10^2 = 314.15926535897932384600 Pi * 15^2 = 706.85834705770347865350 Pi * 25^2 = 1963.49540849362077403750 Pi * 50^2 = 7853.98163397448309615000 */
Normal (Gaussian) distribution example:
$expr = 'normal_distribution(1, $s, $m)'; $calc->defineVar('$s', 1); $calc->defineVar('$m', 0); $calc->registerFunction('normal_distribution', function ($x, $σ = 1, $μ = 0) { $Pi = '3.1415926536'; $p = bcmul( bcdiv( 1, bcmul($σ, pow(bcmul(2, $Pi), 0.5)) ), exp( -bcdiv( pow(bcsub($x, $μ), 2), bcmul(2, pow($σ, 2)) ) ) ); return $p; }); $tokens = $lexer->parse($expr); $nd = $calc->evaluate($tokens);
Testing
$ composer test
Credits
License
The MIT License (MIT).
统计信息
- 总下载量: 7
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-12-26