Sympy 简明教程

SymPy - Substitution

对数学表达式执行的最基本操作之一是替换。SymPy 中的 subs() 函数将第一个参数的所有出现替换为第二个参数。

One of the most basic operations to be performed on a mathematical expression is substitution. The subs() function in SymPy replaces all occurrences of first parameter with second.

>>> from sympy.abc import x,a
>>> expr=sin(x)*sin(x)+cos(x)*cos(x)
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\sin2(x)+\cos2(x)$

$\sin2(x)+\cos2(x)$

>>> expr.subs(x,a)

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$\sin2(a)+\cos2(a)$

$\sin2(a)+\cos2(a)$

如果我们想求某个表达式,此函数非常有用。例如,我们想通过用 5 替换 a 来计算以下表达式的值。

This function is useful if we want to evaluate a certain expression. For example, we want to calculate values of following expression by substituting a with 5.

>>> expr=a*a+2*a+5
>>> expr

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$a^2 + 2a + 5$

$a^2 + 2a + 5$

expr.subs(a,5)

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

The above code snippet gives the following output −

40

40

>>> from sympy.abc import x
>>> from sympy import sin, pi
>>> expr=sin(x)
>>> expr1=expr.subs(x,pi)
>>> expr1

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

The above code snippet gives the following output −

0

0

此函数还用于替换子表达式为另一个子表达式。在以下示例中,将 b 替换为 a+b。

This function is also used to replace a subexpression with another subexpression. In following example, b is replaced by a+b.

>>> from sympy.abc import a,b
>>> expr=(a+b)**2
>>> expr1=expr.subs(b,a+b)
>>> expr1

上面的代码片段给出的输出等同于以下表达式 −

The above code snippet gives an output equivalent to the below expression −

$(2a + b)^2$

$(2a + b)^2$