rodriados/mathr

数学表达式:解析器和评估器。

v3.0 2021-01-04 04:05 UTC

This package is auto-updated.

Last update: 2024-09-06 10:05:00 UTC


README

license MIT version 3.0 Build Status Coverage Status

Mathr是一个快速数学表达式解析器、评估器和计算器,附带一些额外的功能。

使用方法

Mathr最简单的使用方法是发送一个数学表达式。

<?php
$mathr = new Mathr;
$result = $mathr->evaluate("3 + 4 * 5");
echo $result; // 23

您还可以创建自己的变量和函数!

<?php
$mathr->evaluate("v = 10");
$mathr->evaluate("fibonacci(0) = 0");
$mathr->evaluate("fibonacci(1) = 1");
$mathr->evaluate("fibonacci(x) = fibonacci(x - 1) + fibonacci(x - 2)");
$result = $mathr->evaluate("fibonacci(v)");
echo $result; // 55

如果您愿意,可以将函数绑定到原生PHP闭包!

<?php
$mathr->set('triangle(b, h)', fn ($b, $h) => ($b * $h) / 2);
$result = $mathr->evaluate('triangle(5, 8)');
echo $result; // 20

有许多原生函数和变量供您随意使用。

<?php
$mathr->evaluate("fibonacci(x) = ceil((φ ^ x - (1 - φ) ^ x) / sqrt(5))");
$result = $mathr->evaluate("fibonacci(10)");
echo $result; // 55

您可以轻松导出和导入函数和变量。

<?php
$exported = $mathr->export(); // Exports all bound functions and variables.
$mathr->import($exported); // Imports functions and variables.

安装

安装Mathr推荐的方式是通过Composer

{
    "require": {
        "rodriados/mathr": "v3.0"
    }
}