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.
# 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 ))) |
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.
# 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 ))) |
Output:
Using lambda function in SymPy to evaluate squared function : 100