Skip to content

Parsing and evaluating mathematical formulas given as strings.

License

Notifications You must be signed in to change notification settings

brazorf/formula-parser

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Formula Parser

Formula Parser is a library for parsing and evaluating mathematical formulas given as strings.

Supports:

  • Operators: +, -, *, /, ^
  • Variables: x, y, z, a, b
  • Numbers with decimal point '.'
  • Numbers in E notation
  • Constants: pi, e, Inf
  • Functions: sqrt, abs, sin, cos, tan, log, exp
  • Unlimited nested parentheses
  • NaN (Not a Number)

See it in action.

Installation

Requires PHP 5.4 or higher.

To install with Composer:

composer require denissimon/formula-parser

Usage

require_once __DIR__ . '/vendor/autoload.php';

use FormulaParser\FormulaParser;

$formula = '3*x^2 - 4*y + 3/y';
$precision = 2; // Number of digits after the decimal point

try {
    $parser = new FormulaParser($formula, $precision);
    $parser->setVariables(['x' => -4, 'y' => 8]);
    $result = $parser->getResult(); // [0 => 'done', 1 => 16.38]
} catch (\Exception $e) {
    echo $e->getMessage(), "\n";
}

The $precision parameter has a default of 4, and it's not required to specify:

$parser = new FormulaParser('3+4*2/(1-5)^8');
$result = $parser->getResult(); // [0 => 'done', 1 => 3.0001]

The initialized object $parser has the following methods:

setVariables( $array ) Sets variables.

getResult() Returns an array [0 => v1, 1 => v2], where v1 is 'done' or 'error', and v2 is a computed result or error message, respectively.

The error message is issued if a validation error is detected.

getFormula() Returns the text of the formula passed to the constructor.

License

Licensed under the MIT license

About

Parsing and evaluating mathematical formulas given as strings.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%