Python | sympy.lambdify() method

With the help of sympy.lambdify() method, we can convert a SymPy expression to an expression that can be numerically evaluated. lambdify acts like a lambda function, except it, converts the SymPy names to the names of the given numerical 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 can see that by using sympy.lambdify() method, we can get a lambda function from a mathematical expression.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import sympy
from sympy import * 
  
x = symbols('x')
expr = sin(x)
     
# Use sympy.lambdify() method
f = lambdify(x, expr, "math"
    
print("Using lambda function in SymPy to evaluate sin(90) : {}".format(f(90))) 

chevron_right


Output:

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

Example #2:
We can pass a dictionary of sympy_name:numerical_function pair to use lambdify with numerical libraries that it does not know about.

filter_none

edit
close

play_arrow

link
brightness_4
code

# import sympy
from sympy import * 
  
def squared(n) : 
    return n**2
  
x = symbols('x')
expr = x**2
     
# Use sympy.lambdify() method
f = lambdify(x, expr, {"**" : squared}) 
    
print("Using lambda function in SymPy to evaluate squared function : {}".format(f(10))) 

chevron_right


Output:

Using lambda function in SymPy to evaluate squared function : 100


My Personal Notes arrow_drop_up

Coder Machine Learner Social Activist Vocalist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.