SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python and does not require any external libraries.
Symbolic Variables: In SymPy, you work with symbolic variables, which represent mathematical variables in your expressions. These are different from regular Python variables.
Expressions: You can build mathematical expressions using symbolic variables and SymPy functions.
Equations: SymPy can represent equations symbolically, allowing you to solve them analytically or numerically.
Manipulation and Simplification: SymPy can simplify expressions, expand them, factor them, and perform other algebraic manipulations.
Calculus: SymPy supports symbolic calculus, including differentiation, integration, and limit calculations.
Solvers: SymPy contains functions to solve equations algebraically.
Matrix Operations: SymPy can perform various matrix operations including inverse, determinant, etc.
Plotting: SymPy can plot expressions and functions.
# Example 1: Defining and Manipulating Symbolic Variables
from sympy import symbols
x, y = symbols('x y')
expr = x + 2*y
expr
expr.subs(y, 1)
# Example 2: Solving Equations
from sympy import Eq, solve
sol1 = solve(x**2 - 1, x)
print(sol1)
sol2 = solve([x**2-y**2, x+y], (x, y))
print(sol2)
[-1, 1] [(-y, y)]
# Example 3: Differentiation
from sympy import diff
expr = x**2 + x*y
diff_expr = diff(expr, x)
diff_expr
# Example 4: Integration
from sympy import integrate
expr = x**2
integral_expr = integrate(expr, x)
integral_expr
# Example 5: Matrix Operations
from sympy import Matrix
matrix = Matrix([[1, 2], [3, 4]])
matrix_inv = matrix.inv()
matrix_inv
# Example 6: Solving a Differential Equation
from sympy import Function, dsolve, Derivative, sin
y = Function('y')
diff_eq = Derivative(y(x), x, x) - 2*Derivative(y(x), x) + y(x) - sin(x)
solution = dsolve(diff_eq, y(x))
solution
Execute the following:
from sympy import diff, cos, exp
C1, C2 = symbols('C1 C2')
y = (C1 + C2*x) * exp(x) + cos(x)/2
print(y.subs(x, 0))
print(diff(y, x).subs(x, 0))
Find $C_1$ and $C_2$ so that $y(0) = y'(0) = 0$.
from sympy import diff, cos, exp
C1, C2 = symbols('C1 C2')
y = (C1 + C2*x) * exp(x) + cos(x)/2
print(y.subs(x, 0))
print(diff(y, x).subs(x, 0))
C1 + 1/2 C1 + C2
# Example 7: lambdify
from sympy import lambdify, cos, exp
y = (-1/2 + (1/2)*x) * exp(x) + cos(x)/2
func = lambdify(x, y)
func(1)
0.2701511529340699
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")
grid = np.linspace(0, 10, 100)
plt.plot(grid, [func(x) for x in grid])
plt.show()