Giter Club home page Giter Club logo

formula-parser's Introduction

Formula Parser

Latest Stable Version Total Downloads License

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)

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:

setValidVariables($array) Overwrites default valid variables.

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 validation error message, respectively.

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

More usage examples can be found in tests/FormulaParserTest.php

License

Licensed under the MIT license

formula-parser's People

Contributors

brazorf avatar denissimon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formula-parser's Issues

Add more variables

Is it possible to add more variables?
If yes, then which letters/characters should not be used?

Very interesting code you have here,
Thanks

Problem when variable is next to number

Hey @denissimon great work.
I have a small issue when trying to evaluate an expression.
If i give the expression 3 * 6x (between 6 and 'x' there is no operator or space), and set Variable 'x' to 1, then i get the result 3. Which means that somehow, it ignores the number 6, and evaluates the expression 3 * x. (i used 'x' as 2 and i get as result 6).
But when i give the expression 3 * x6, i get a syntax error, as expected. Shouldn't i get a syntax error as well in the first case? Why it ignores the number given before the variable, when there is neither operator or space between them?

Cheers

Support for ceil

Hi, I have been using your library for year now for the complex computation of our loan system and its was great. Appreciate your effort on this.

But would you mind if you can add a support to ceil the result, so I dont need to add ceil on every result

thanks,

Parse IF operator

Hi @denissimon great work!

Any clue on how to parse something like this:
if(condition;action1;action2), if(condition;action1;if(condition;action1;action2)), etc?

Thanks

FEATURE REQUEST: Custom Functions

It would be useful to have custom functions, I am attempting to mod this, but the parse method isn't exactly built for dynamic customization, it uses exact pre-defined string lengths.

an example like

->addFunction('min', function($value, $arg) {
    return min($value, $arg)
});

While this is a basic example, it would be very useful to have functions passing in the value and a single argument.

strstr(): Empty needle

Hi there,

I got a error like:

[2]strstr(): Empty needle[.../vendor/denissimon/formula-parser/FormulaParser.php:301

And I found this:

private function combine($array) {
        $new_array = [];
        $i = $j = $key = 0;

        foreach ($array as $item) {

            $array_ip1 = (isset($array[$i+1])) ? $array[$i+1] : null;

            end($new_array);
            $cur = current($new_array);

            if ((@strstr('+-', (string) $item)) && (@strstr('+-', (string) $cur)) 
            && (@strstr('+-', (string) $array_ip1))) {
                if ($item === '-')
                    $new_array[key($new_array)] = ($cur == '+') ? '-' : '+';
            } elseif ((@strstr('+-', (string) $item)) && (@strstr('*/^', (string) $cur)) 
            && (@strstr('+-', (string) $array_ip1))) {
                $new_array[] = $item;
            } else {
                if ((@strstr('+-', (string) $item)) && ($key+1 != $i) 
                && (@strstr('*/^', (string) $array[$key]))
                && (!is_numeric($array[$key+1])) && (isset($array[$key+1]))) {
                    if ($item === '-')
                        $new_array[key($new_array)] = ($cur == '+') ? '-' : '+';
                } else {
                    $new_array[] = $item;
                    $key = $i;
                }
            }
            $i++;
        }
// ...
}

when foreach run, $new_array is empty, and (string) $cur got a empty string.

so strstr() give me a error.

Uninitialized string offset

Hi!
I'm getting this error:
Uninitialized string offset: 2:620 in FormulaParser.
Analyzed the sources but I can't understand why I'm getting this. The formula is x-y+2
Please help, thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.