Answer the question
In order to leave comments, you need to log in
PHP Math Lexer?
Hello to all habrasociety.
Can you please tell me if there is any universal mathematical parser in PHP?
The essence of the problem:
There is a simple string, which contains numbers, functions, operands. For example: 0.85 + 1.15
(2^3 - 200) * 2
abs(-100) + sin(0.75) - 2
2*3*(0.55 + 0.15) / 100
And it is necessary to return the result of executing this line as a mathematical expression.
All these lines will be stored in the database, and as a result, the idea arose to find (write) a mathematical parser.
There are also some wishes:
1. Implementation of variables.
$mathParser = new MathParser(':a * :b');
$mathParser
->setVariable('a', 0.25)
->setVariable('b', 0.35);
$result = $mathParser->getResult();
$mathParser = new MathParser('my_func(:a)');
$mathParser
->setVariable('a', $myVariable)
->addFunction('my_func', function($a) { return abs($a); } );
$result = $mathParser->getResult();
Answer the question
In order to leave comments, you need to log in
Well, take MathExecutor, it is very simple, you can easily add your own functions.
I implemented my own (but in C ++) something in a couple of days, in fact, Reverse Polish Notation is very easy to process, and converting a regular notation to OPV is nothing complicated, the algorithms are all described on the internet.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question