SymPy - Lambdify() function



The lambdify function translates SymPy expressions into Python functions. If an expression is to be evaluated over a large range of values, the evalf() function is not efficient. lambdify acts like a lambda function, except it converts the SymPy names to the names of the given numerical library, usually NumPy. By default, lambdify on implementations in the math standard library.

>>> expr=1/sin(x) 
>>> f=lambdify(x, expr) 
>>> f(3.14)

The above code snippet gives the following output −

627.8831939138764

The expression might have more than one variables. In that case, first argument to lambdify() function is a list of variables, followed by the expression to be evaluated.

>>> expr=a**2+b**2 
>>> f=lambdify([a,b],expr) 
>>> f(2,3)

The above code snippet gives the following output −

13

However, to leverage numpy library as numerical backend, we have to define the same as an argument for lambdify() function.

>>> f=lambdify([a,b],expr, "numpy")

We use two numpy arrays for two arguments a and b in the above function. The execution time is considerably fast in case of numpy arrays.

>>> import numpy 
>>> l1=numpy.arange(1,6) 
>>> l2=numpy.arange(6,11) 
>>> f(l1,l2)

The above code snippet gives the following output −

array([ 37, 53, 73, 97, 125], dtype=int32)

Advertisements