Simple Start Notebook for SymPy
Importing SymPy¶
First, you need to import the SymPy library and initialize it:
In [ ]:
from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)
Basic Algebraic Operations¶
You can perform basic arithmetic operations like addition, subtraction, multiplication, and division:
In [ ]:
# Addition
expr1 = x + y
# Subtraction
expr2 = x - y
# Multiplication
expr3 = x * y
# Division
expr4 = x / y
print(f"{expr1}\t{expr2}\t{expr3}\t{expr4}")
Simplification¶
To simplify expressions, use the simplify() function:
In [ ]:
# Simplifying an expression
expr = (x**2 - y**2) / (x - y)
simplified_expr = simplify(expr)
simplified_expr
Expanding and Factoring¶
You can expand and factor polynomials using expand() and factor():
In [ ]:
# Expanding a polynomial
polynomial = (x + y)**2
expanded_polynomial = expand(polynomial)
print(expanded_polynomial)
# Factoring a polynomial
factored_polynomial = factor(x**2 - y**2)
print(f"\n{factored_polynomial}")
Solving Equations¶
To solve equations, use the solve() function:
In [ ]:
equation = Eq(x**2 + 2*x + 1, 0)
solutions = solve(equation, x)
solutions
Working with Polynomials¶
You can create and manipulate polynomials easily
In [ ]:
# Creating a polynomial
poly3 = poly(x**3 + 2*x**2 + x + 1)
# Getting the degree of the polynomial
degree = poly3.degree()
# Coefficients of the polynomial
coefficients = poly3.all_coeffs()
print(f"Degree: {degree}\tcoefficients:{coefficients}")
Example: Full Computation¶
Here’s a complete example that combines several operations:
In [ ]:
# Define symbols
x, y = symbols('x y')
# Define an expression
expr = x**2 + 2*x + 1
# Simplify the expression
simplified = simplify(expr)
# Expand the expression
expanded = expand((x + 1)**2)
# Solve the equation
equation = Eq(x**2 + 2*x + 1, 0)
solutions = solve(equation, x)
# Output results
print("Simplified:", simplified)
print("Expanded:", expanded)
print("Solutions:", solutions)