Equations
In this section, the equations are expanded and also can be factorized and even equations can be simplified using expand, factor and simplify methods respectively. In addition to the specified operations, we can also solve equations and perform substitution in the equations. All these topics are explained below with examples.
Example 1: Expanding equation
Here first an expression/equation is created i.e., 3P+6Q-R by declaring symbols P, Q, R, and expand() method is used by multiplying P with expression.
Syntax expand(expression)
where expression is a mathematical equation
Python3
from sympy import * P, Q, R = symbols( "P Q R" ) expression = 3 * P + 6 * Q - R expanded_exp = expand(P * expression) expanded_exp |
Output
Example 2: Factor the equation
Here the expanded expression 3P^2+6PQ-PR is factored into P(3P+6Q-R) using the factor() method.
Syntax: factor(expanded_expression)
where expanded_expression is the expression we need to factor.
Python3
from sympy import * P, Q, R = symbols( "P Q R" ) expression = 3 * P + 6 * Q - R # 3P+6Q-R expanded_exp = expand(P * expression) # 3P^2+6PQ-PR factor(expanded_exp) |
Output
Example 3: Simplifying the equation
The expression \frac{3P2+9}{3} is simplified to P2+3 using simplify() method
Syntax: simplify(expression)
where expression is the any mathematical expression/equation.
Python3
from sympy import * P = Symbol( "P" ) expression = ( 3 * P * * 2 + 9 ) / 3 # (3P^2+9)/3 simplified_exp = simplify(expression) simplified_exp |
Output
Example 4: Solving equations
The solve() method returns list of integers containing roots of the equation.
Syntax: solve(equation, symbol)
where equation represents expression/equation to solve,
symbol is the variable present in the equation
Python3
from sympy import * P = Symbol( "P" ) expression = (P * * 2 + 3 * P - 4 ) / 3 # P^2+3P-4 solve(expression, P) |
Output
[-4,1]
Example 5: Substitution
Here we will subs() method to apply substitution within the equation.
Syntax: expression.subs(symbol, constant)
where expression holds the equation we are applying substitution.
- symbol is the variable present in the equation.
- constant is the value that is replacing the symbol.
Python3
from sympy import * P = Symbol( "P" ) expression = (P * * 2 + 3 * P - 4 ) # P^2+3P-4 expression.subs(P, 3 ) |
Output
14
What is Symbolic Computation in SymPy?
In this article, we are going to see how to perform symbolic computation in Sympy in Python.
Symbolic Computation in Sympy is used to solve mathematical expressions by integrating mathematics with computer science using mathematical symbols. It manipulates mathematical objects and expressions. Sympy evaluates algebraic expressions exactly using traditional mathematical symbols but not approximately.
Let’s look into an example to differentiate Sympy mathematical operation and normal mathematical operation.