Every SymPy task starts by declaring symbols and building expressions from them.
SymPy is a computer algebra system: instead of computing numbers, it manipulates formulas. The building block is a symbol, a named mathematical variable created with symbols():
from sympy import symbols
x, y = symbols("x y")Ordinary Python operators on symbols build expression trees rather than values. x**2 + 2*x*y is an Add object whose arguments are a Pow and a Mul. SymPy applies only obvious, cheap simplifications automatically: x + x becomes 2*x and x * 0 becomes 0, but (x + 1)**2 is left alone until you ask for expand().
A few rules to remember from day one:
- Use
**for powers.^is Python's XOR and raises aTypeErrorwith symbols. - The Python variable name and the symbol name are independent:
a = symbols("b")works but is confusing, so keep them equal. - Expressions are immutable. Methods like
subsorexpandreturn a new expression; the original never changes. expr.free_symbolslists the symbols an expression depends on.
print() gives a plain string form that is valid Python, while pprint() draws a 2D ASCII or Unicode rendering. In Jupyter, init_printing() makes results render as typeset math automatically.
Example
from sympy import symbols, pprint
x, y = symbols("x y")
expr = x**2 + 2*x*y + x
print(expr) # x**2 + 2*x*y + x
print(expr + x) # x**2 + 2*x*y + 2*x
print(expr * 0) # 0
print((x + 1)**2) # (x + 1)**2 (not expanded automatically)
print(type(expr).__name__) # Add
print(sorted(map(str, expr.free_symbols))) # ['x', 'y']
pprint(x**2 / y, use_unicode=False)
# 2
# x
# --
# yRemember
- symbols("x y") creates symbol objects; operators build expression trees
- Only trivial simplifications happen automatically
- Use ** for powers; expressions are immutable
Watch out for
- Writing x^2 instead of x**2: ^ is bitwise XOR in Python.