English 中文(简体)
SymPy - Lambdify() function
  • 时间:2024-12-22

SymPy - Lambdify() function


Previous Page Next Page  

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 pke a lambda function, except it converts the SymPy names to the names of the given numerical pbrary, usually NumPy. By default, lambdify on implementations in the math standard pbrary.


>>> 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 pst 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 pbrary 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