Python | sympy.lambdify () method

With the sympy.lambdify () method, we can convert the SymPy expression into an expression that can be evaluated numerically.  lambdify acts like a lambda function, except that it converts SymPy names to the names of a given numeric library, usually NumPy or math .

Syntax: lambdify (variable, expression, library)

Parameters:
variable – It is the variable in the mathematical expression.
expression – It is the mathematical expression which is converted into its respective name in the given library .
library – It is the Python library to which expression is to be converted into.

Returns: Returns a lambda function which can evaluate a mathematical expression.

Example # 1:
In this example, we see that with the sympy.lambdify () method we can get a lambda function from a mathematical expression.

 

# import sympy

from sympy import *  

 

x = symbols ( `x` )

expr = sin (x)

 
# Use the sympy.lambdify () method

f = lambdify (x, expr, "math"

 

print ( "Using lambda function in SymPy to evaluate sin (90): {}" . format (f ( 90 ))) 

Exit :

 Using lambda function in SymPy to evaluate sin (90): 0.893996663601 

Example # 2:
We can pass a dictionary of sympy_name: numeric_function pairs to use lambdify with numeric libraries he doesn`t know about.

# import sympy

from sympy import *  

 

def squared (n):  < / p>

return n * * 2

  

x = symbols ( `x` )

expr = x * * 2

 
# Use the sympy method .lambdify ()

f = lambdify (x, expr, { "**" : squared}) 

 

print ( "Using lambda function in SymPy to evaluate squared function: {}" . format (f ( 10 ))) 

Output:

 Using lambda function in SymPy to evaluate squared function: 100