sufir/php-calc

Simple calculation expressions

1.0.3 2016-01-04 09:58 UTC

This package is not auto-updated.

Last update: 2024-12-21 20:08:36 UTC


README

Latest Version on Packagist Build Status Quality Score Coverage Status Issues Software License

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).