1. Defining Symbols
To work with expressions in SymPy, you need to define variables (symbols). Use the symbols() function.
from sympy import symbols
x, y = symbols('x y') # Define x and y as symbols
z = symbols('z') # Define z as a symbol (eigenvalues)
2. Creating and Displaying Expressions
Create expressions using the defined symbols.
xpression = x + 2*y - z
print(expression) # Display the expression
3. Evaluating Expressions (Substitution)
Use the subs() method to substitute values for symbols and evaluate the expression.
result = expression.subs({x: 1, y: 2, z: 3})
print(result) # Display the evaluated expression
4. Expanding and Factoring Expressions
Expanding: Use the expand() function.
expression = (x + y)**2
expanded_expression = expression.expand()
print(expanded_expression) # Display the expanded expression
Factoring: Use the factor() function.
expression = x**2 - y**2
factored_expression = expression.factor()
print(factored_expression) # Display the factored expression
5. Simplifying Expressions
Use the simplify() function to simplify an expression as much as possible.
expression = (x**2 + 2*x + 1) / (x + 1)
simplified_expression = expression.simplify()
print(simplified_expression) # Display the simplified expression
6. Calculus
Differentiation: Use the diff() function.
from sympy import diff
expression = x**3 + 2*x**2 - x + 5
derivative = diff(expression, x) # Differentiate with respect to x
print(derivative) # Display the derivativeIntegration: Use the integrate() function.
from sympy import integrate
expression = x**2
integral = integrate(expression, x) # Integrate with respect to x
print(integral) # Display the integral