Try Math ParserTable of ContentsSoftware
Evaluate Mathematical Expressions in Python

Evaluate Mathematical Expressions
in Python

Python is an interpreted language and it does have an eval() function that makes evaluating a Python expression easier. Unlike compiled languages, in Python, we do not need to re-invent the wheel to write a math parser for this purpose. Parsing of the expression is done by Python at runtime.

If you do not care about the AST (Abstract Syntax Tree) of the expression, you can simply pass a string expression to the eval() function to get the value. The expression syntax will be limited to what the Python language supports.

For example:

eval(�1+3�)

However, in many situations, you need to collect input from the user and evaluate it as a mathematical expression. If you have a web application running on the server side, a malicious user can type a function call that can have undesired side effects when evaluated with the eval() Python function. To guard for this security hole, you need a way to limit what functions and variables the user can actually use.

PyMathParser - Evaluate Math Expression

Bestcode is pleased to introduce PyMathParser Python class that simplifies the math expression evaluation for you. PyMathParser maintains a list of permitted functions and variables to limit Python�s eval() function to these symbols only.

The Math Parser Component is also available on many platforms/languages such as:

Example of Evaluating a Formula using PyMathParser

Here is the code for PyMathParser that is used to evaluate a mathematical expression in a safe way:


from math import *

class PyMathParser(object):
    '''
    Mathematical Expression Evaluator class.
    You can set the expression member, set the functions, variables and then call
    evaluate() function that will return you the result of the mathematical expression
    given as a string.
    '
''
   
    '''
    Mathematical expression to evaluate.
    '
''
    expression = ''
   
    '''
    Dictionary of functions that can be used in the expression.
    '
''
    functions = {'__builtins__':None};
   
    '''
    Dictionary of variables that can be used in the expression.
    '
''
    variables = {'__builtins__':None};

    def __init__(self):
        '''
        Constructor
        '
''
   
    def evaluate(self):
        '''
        Evaluate the mathematical expression given as a string in the expression member variable.
       
        '
''
        return eval(self.expression, self.variables, self.functions);

    def addDefaultFunctions(self):
        '''
        Add the following Python functions to be used in a mathemtical expression:
        acos
        asin
        atan
        atan2
        ceil
        cos
        cosh
        degrees
        exp
        fabs
        floor
        fmod
        frexp
        hypot
        ldexp
        log
        log10
        modf
        pow
        radians
        sin
        sinh
        sqrt
        tan
        tanh
        '
''
        self.functions['acos']=acos
        self.functions['asin']=asin
        self.functions['atan']=atan
        self.functions['atan2']=atan2
        self.functions['ceil']=ceil
        self.functions['cos']=cos
        self.functions['cosh']=cosh
        self.functions['degrees']=degrees
        self.functions['exp']=exp
        self.functions['fabs']=fabs
        self.functions['floor']=floor
        self.functions['fmod']=fmod
        self.functions['frexp']=frexp
        self.functions['hypot']=hypot
        self.functions['ldexp']=ldexp
        self.functions['log']=log
        self.functions['log10']=log10
        self.functions['modf']=modf
        self.functions['pow']=pow
        self.functions['radians']=radians
        self.functions['sin']=sin
        self.functions['sinh']=sinh
        self.functions['sqrt']=sqrt
        self.functions['tan']=tan
        self.functions['tanh']=tanh
       
    def addDefaultVariables(self):
        '''
        Add e and pi to the list of defined variables.
        '
''
        self.variables['e']=e
        self.variables['pi']=pi

    def getVariableNames(self):
        '''
        Return a List of defined variables names in sorted order.
        '
''
        mylist = list(self.variables.keys())
        try:
            mylist.remove('__builtins__')
        except ValueError:
            pass
        mylist.sort()
        return mylist


    def getFunctionNames(self):
        '''
        Return a List of defined function names in sorted order.
        '
''
        mylist = list(self.functions.keys())
        try:
            mylist.remove('__builtins__')
        except ValueError:
            pass
        mylist.sort()
        return mylist
   
 

Simple Python Unit Test for PyMathParser

Here is the unit test that shows how to invoke PyMathParser to evaluate a user defined formula given as a string:

'''
Unit tests for PyMathParser.
'
''
import unittest
from bcmathparser import MathParser
from math import *

class Test(unittest.TestCase):

    def setUp(self):
        self.mathparser = MathParser.PyMathParser()
        self.mathparser.addDefaultFunctions()
        self.mathparser.addDefaultVariables()
        self.mathparser.variables['x'] = 1.5;
        self.mathparser.variables['y'] = 2.0;


    def tearDown(self):
        pass

    def testBasic(self):
        self.mathparser.expression = '1+ 2'
        val = self.mathparser.evaluate()
        self.assertEquals(3, val)
        print val

    def testEvalExpression(self):
        self.mathparser.expression = '1+ 2+sin (x+ y)/e+pi'
        print self.mathparser.evaluate()

    def testNegativeFailNoFunction(self):
        self.mathparser.expression = '1+2+sin( x + y)/abc(x)'
        try:
            print self.mathparser.evaluate()
        except NameError as (err):
            if (err.message!="name 'abc' is not defined"):
                raise err
            print 'Expected error: ', err #expected error: name 'abc' is not defined

    def testFunctionNames(self):
        print self.mathparser.getFunctionNames()

    def testVariableNames(self):
        print self.mathparser.getVariableNames()

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()
 

PyMathParser Class Documentation Generated by PyDoc

 
 
bcmathparser.MathParser

Mathematical Expression Evaluator class for Python.
You can set the expression member, set the functions, variables and then call
evaluate() function that will return you the result of the mathematical expression
given as a string. 
 
The user is granted rights to user, distribute and/or modify the source code 
as long as this notice is shipped with it.
 
The Author of this software cannot and do not warrant that any 
functions contained in the Software will meet your requirements, 
or that its operations will be error free. 
 
The entire risk as to the Software performance or quality, 
or both, is solely with the user and not the Author.
 
You assume responsibility for the selection of the software to 
achieve your intended results, and for the installation, use, and 
results obtained from the Software. 
 
The Author makes no warranty, either implied or expressed, including 
with-out limitation any warranty with respect to this Software 
documented here, its quality, performance, or fitness for a particular 
purpose. In no event shall the Author be liable to you for damages, 
whether direct or indirect, incidental, special, or consequential 
arising out the use of or any defect in the Software, even if the 
Author has been advised of the possibility of such damages, 
or for any claim by any other party. 
 
All other warranties of any kind, either express or implied, 
including but not limited to the implied warranties of 
merchantability and fitness for a particular purpose, are expressly 
excluded.
 
Copyright and all rights of this software, irrespective of what
has been deposited with the U.S. Copyright Office, belongs
to Bestcode.com.

 
Classes
       
__builtin__.object
PyMathParser

 
class PyMathParser(__builtin__.object)
    Mathematical Expression Evaluator class.
You can set the expression member, set the functions, variables and then call
evaluate() function that will return you the result of the mathematical expression
given as a string.
 
  Methods defined here:
__init__(self)
Constructor
addDefaultFunctions(self)
Add the following Python functions to be used in a mathemtical expression:
acos
asin
atan
atan2
ceil
cos
cosh
degrees
exp
fabs
floor
fmod
frexp
hypot
ldexp
log
log10
modf
pow
radians
sin
sinh
sqrt
tan
tanh
addDefaultVariables(self)
Add e and pi to the list of defined variables.
evaluate(self)
Evaluate the mathematical expression given as a string in the expression member variable.
getFunctionNames(self)
Return a List of defined function names in sorted order.
getVariableNames(self)
Return a List of defined variables names in sorted order.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Data and other attributes defined here:
expression = ''
functions = {'__builtins__': None}
variables = {'__builtins__': None}

 
Functions
       
acos(...)
acos(x)
 
Return the arc cosine (measured in radians) of x.
acosh(...)
acosh(x)
 
Return the hyperbolic arc cosine (measured in radians) of x.
asin(...)
asin(x)
 
Return the arc sine (measured in radians) of x.
asinh(...)
asinh(x)
 
Return the hyperbolic arc sine (measured in radians) of x.
atan(...)
atan(x)
 
Return the arc tangent (measured in radians) of x.
atan2(...)
atan2(y, x)
 
Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.
atanh(...)
atanh(x)
 
Return the hyperbolic arc tangent (measured in radians) of x.
ceil(...)
ceil(x)
 
Return the ceiling of x as a float.
This is the smallest integral value >= x.
copysign(...)
copysign(x,y)
 
Return x with the sign of y.
cos(...)
cos(x)
 
Return the cosine of x (measured in radians).
cosh(...)
cosh(x)
 
Return the hyperbolic cosine of x.
degrees(...)
degrees(x) -> converts angle x from radians to degrees
exp(...)
exp(x)
 
Return e raised to the power of x.
fabs(...)
fabs(x)
 
Return the absolute value of the float x.
factorial(...)
factorial(x) -> Integral
 
Find x!. Raise a ValueError if x is negative or non-integral.
floor(...)
floor(x)
 
Return the floor of x as a float.
This is the largest integral value <= x.
fmod(...)
fmod(x,y)
 
Return fmod(x, y), according to platform C.  x % y may differ.
frexp(...)
frexp(x)
 
Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
fsum(...)
sum(iterable)
 
Return an accurate floating point sum of values in the iterable.
Assumes IEEE-754 floating point arithmetic.
hypot(...)
hypot(x,y)
 
Return the Euclidean distance, sqrt(x*x + y*y).
isinf(...)
isinf(x) -> bool
Checks if float x is infinite (positive or negative)
isnan(...)
isnan(x) -> bool
Checks if float x is not a number (NaN)
ldexp(...)
ldexp(x, i) -> x * (2**i)
log(...)
log(x[, base]) -> the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(...)
log10(x) -> the base 10 logarithm of x.
log1p(...)
log1p(x)
 
Return the natural logarithm of 1+x (base e).
      The result is computed in a way which is accurate for x near zero.
modf(...)
modf(x)
 
Return the fractional and integer parts of x.  Both results carry the sign
of x and are floats.
pow(...)
pow(x,y)
 
Return x**y (x to the power of y).
radians(...)
radians(x) -> converts angle x from degrees to radians
sin(...)
sin(x)
 
Return the sine of x (measured in radians).
sinh(...)
sinh(x)
 
Return the hyperbolic sine of x.
sqrt(...)
sqrt(x)
 
Return the square root of x.
tan(...)
tan(x)
 
Return the tangent of x (measured in radians).
tanh(...)
tanh(x)
 
Return the hyperbolic tangent of x.
trunc(...)
trunc(x:Real) -> Integral
 
Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

 
Data
        e = 2.7182818284590451
pi = 3.1415926535897931
 

Download PyMathParser for FREE

You can download PyMathParser source code for free.

 

webmaster@gobestcode.com