Python| sympy.lambdify() 方法
借助sympy.lambdify()方法,我们可以将SymPy表达式转换为可以数值计算的表达式。 lambdify的作用类似于 lambda函数,除了它将SymPy名称转换为给定数值库的名称,通常是NumPy或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.
示例 #1:
在这个例子中,我们可以看到通过使用sympy.lambdify()方法,我们可以从数学表达式中得到一个 lambda函数。
# 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)))
输出:
Using lambda function in SymPy to evaluate sin(90) : 0.893996663601
示例 #2:
我们可以传递一个sympy_name:numerical_function 对的字典,以将 lambdify 与它不知道的数字库一起使用。
# 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)))
输出:
Using lambda function in SymPy to evaluate squared function : 100