SymPy – Substitution
”;
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 −
$sin^2(x)+cos^2(x)$
>>> expr.subs(x,a)
The above code snippet gives an output equivalent to the below expression −
$sin^2(a)+cos^2(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$
expr.subs(a,5)
The above code snippet gives the following output −
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
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$
”;