- SymPy - Discussion
- SymPy - Useful Resources
- SymPy - Quick Guide
- SymPy - Printing
- SymPy - Sets
- SymPy - Entities
- SymPy - Plotting
- SymPy - Solvers
- SymPy - Quaternion
- SymPy - Function class
- SymPy - Matrices
- SymPy - Integration
- SymPy - Derivative
- SymPy - Simplification
- SymPy - Querying
- SymPy - Logical Expressions
- SymPy - Lambdify() function
- SymPy - evalf() function
- SymPy - sympify() function
- SymPy - Substitution
- SymPy - Symbols
- SymPy - Numbers
- SymPy - Symbolic Computation
- SymPy - Installation
- SymPy - Introduction
- SymPy - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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$
Advertisements