sympy.subs() method in Python is used to substitute a variable or expression with a specified value or another expression in a symbolic mathematical expression. It is part of the SymPy library, which provides functionality for symbolic mathematics in Python, allowing you to work with equations, polynomials, integrals, and more.
Example: Basic Variable Substitution Using sympy.subs()
This example demonstrates how to substitute one variable with another symbolic variable in an expression.
# import sympy
from sympy import *
x, y = symbols('x y')
exp = x**2 + 1
print("Before Substitution : {}".format(exp))
# Use sympy.subs() method
res_exp = exp.subs(x, y)
print("After Substitution : {}".format(res_exp))
Output
Before Substitution : x**2 + 1
After Substitution : y**2 + 1
Explanation:
The code uses SymPy to create symbolic variables x and y. The expression x**2 + 1 is defined. The subs() method is used to replace x with y in the expression.
- Initially, the expression is x**2 + 1.
- After substitution, x is replaced by y, resulting in the expression y**2 + 1.
Syntax
sympy.subs(old, new)
Parameters
- old: The variable or expression to be replaced.
- new: The value or expression that will replace the old variable or expression.
Return Value
The method returns a new expression with the substitution made. It does not modify the original expression but returns a new expression where the substitution is applied.
Examples of sympy.subs() method
1. Substitute with a Numeric Value Using sympy.subs()
This example shows how to substitute a variable with a numeric value (0 in this case) in a mathematical expression.
# import sympy
from sympy import *
x = symbols('x')
exp = cos(x) + 7
print("Before Substitution : {}".format(exp))
# Use sympy.subs() method
res_exp = exp.subs(x, 0)
print("After Substitution : {}".format(res_exp))
Output
Before Substitution : cos(x) + 7
After Substitution : 8
Explanation:
- x = symbols('x'): Creates a symbolic variable x.
- exp = cos(x) + 7: Creates an expression cos(x) + 7 using the symbolic variable x.
- exp.subs(x, 0): Substitutes x with 0 in the expression cos(x) + 7.
2. Multiple Variable Substitution Using sympy.subs()
This example illustrates how to perform multiple variable substitutions simultaneously using a list of tuples in the subs() method.
# import sympy
from sympy import *
x, y, z = symbols('x y z')
exp = x**2 + 7 * y + z
print("Before Substitution : {}".format(exp))
# Use sympy.subs() method
res_exp = exp.subs([(x, 2), (y, 4), (z, 1)])
print("After Substitution : {}".format(res_exp))
Output
Before Substitution : x**2 + 7*y + z
After Substitution : 33
Explanation: The code defines the symbolic variables x, y, and z using SymPy. It then creates an expression x**2 + 7 * y + z, and substitutes values for x, y, and z using the subs() method.