pythonmathsympyequationmath.js

Converting Math.js-like Expressions to Runnable Python Code


Im trying to convert a string I got from math.js (for example 2*x^2+5x-1 ) to a runnable python function that looks something like this:

def f(x):
   return 2*(x**2)+5*x-1

I've experimented with sympify from the sympy module:

from sympy import sympify, symbols

x = symbols("x")
expression = "x**2 + 3*x-1"
print(sympify(expression).subs(x, 2))

However, this approach fails to handle certain operations like ^ and only returns the result. Additionally, I've tried using the eval() function, encountering similar issues.


Solution

  • SymPy has a in-build parser to translate a string into a SymPy expression. Use for ex subs or lambdify for evaluation.

    Some further parsing rules can be passed via the transformations parameter such as implicit multiplication, i.e. 5x -> 5*x, here the full list.

    from sympy import parse_expr
    from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
    
    # tuple of transformations
    transformations = (
        standard_transformations +
        (implicit_multiplication_application,))
    
    
    s = '2*x^2 + 5x - 1'.replace('^', '**')
    e = parse_expr(s, transformations=transformations)
    
    # check object
    print(e)
    # 2*x**2 + 5*x - 1
    print(type(e))
    #<class 'sympy.core.add.Add'>