SymPy is the SciPy ecosystem’s library for symbolic mathematics: it manipulates expressions exactly, like a free Mathematica built on Python. Where NumPy gives you numbers, SymPy gives you formulas: it can expand, factor, differentiate, integrate, and solve algebraically. Before a variable can appear in an expression it must be declared a symbol with symbols().
Algebra¶
The everyday manipulations are expand, factor, and simplify.
To solve an equation (SymPy sets the expression equal to zero), use solve:
Calculus¶
Differentiate with diff: the first argument is the expression, the rest are the variables to differentiate by. Repeating a variable (or giving a number) takes higher derivatives.
Integrate with integrate. With no limits you get an antiderivative; with limits, a definite integral. The symbol oo means infinity, so the Gaussian integral central to quantum mechanics is one line:
A Taylor series expansion uses series. By default it expands about ; extra arguments set the center and the order.
A quantum-mechanical example: hydrogen radial functions¶
SymPy ships the hydrogen atom’s exact wavefunctions in its physics module. Here we pull the radial function , find the radius where the radial probability density peaks, and plot it. This is a worked symbolic-to-numeric pipeline: solve exactly, then lambdify into a NumPy function to plot.
The peak of the radial density sits at , exactly the Bohr-model radius of the orbit.
Exercises¶
Factor .
Expand .
Evaluate with
integrate(uselog(4)for the upper limit).The reversible isothermal work of a gas is . Integrate it symbolically, then evaluate for mol, K, L, L.