Sympy 简明教程

SymPy - Lambdify() function

lambdify 函数将 SymPy 表达式转换为 Python 函数。如果要在较大的值范围内求解表达式,则 evalf() 函数效率不高。lambdify 就像一个 lambda 函数,但它会将 SymPy 名称转换为给定数值库的名称,通常是 NumPy。默认情况下,lambdify 对 math 标准库中的实现进行操作。

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

>>> expr=1/sin(x)
>>> f=lambdify(x, expr)
>>> f(3.14)

上面的代码段给出了以下输出:

The above code snippet gives the following output −

627.8831939138764

627.8831939138764

该表达式可能具有多个变量。在这种情况下,lambdify() 函数的第一个参数是变量列表,后跟要计算的表达式。

The expression might have more than one variables. In that case, first argument to lambdify() function is a list 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

13

然而,要利用 numpy 库作为数值后端,我们必须将其定义为 lambdify() 函数的参数。

However, to leverage numpy library as numerical backend, we have to define the same as an argument for lambdify() function.

>>> f=lambdify([a,b],expr, "numpy")

我们在上述函数中为两个参数 a 和 b 使用了两个 numpy 数组。对于 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)

array([ 37, 53, 73, 97, 125], dtype=int32)