A computer algebra system does not “read a formula” — it builds a tree from it and transforms that tree according to rules.
x**2 + 1 in SymPy, we get the object Add(Pow(Symbol('x'), Integer(2)), Integer(1)):
a tree whose nodes are operations and whose leaves are numbers and symbols. While building the tree, the CAS already performs
automatic simplifications (it combines numbers and like terms, and orders the arguments). Polynomials have a
canonical form — after expansion, two equal polynomials have identical trees. For expressions with sin,
exp or sqrt, no such form exists in general.
Number of tree nodes before expansion (gray) and after expansion (indigo), logarithmic scale.
The compact form $(x+y+z)^n$ always has 6 nodes, while the expanded form has $\binom{n+2}{2}$ terms — canonicity comes at a price.
That is why a CAS does not expand anything “on its own”, only on request (expand).
1. The parser. The text is turned into a tree according to operator precedence: exponentiation binds most tightly (and from the right: $2^{3^2} = 2^9$), then multiplication and division, and finally addition and subtraction; unary minus binds more weakly than a power ($-2^2 = -4$). Turn off automatic simplification to see the raw parse tree.
2. The CAS object. SymPy has only a few kinds of nodes: Add and Mul (with any number of arguments), Pow,
functions, and leaves. Subtraction and division are rewritten: $x - y = x + (-1)\cdot y$, $\;x/y = x\cdot y^{-1}$. As a result there are fewer rules, and comparing trees is simpler.
3. Canonical form. A function $c$ is canonical if for expressions $f, g$ we have
$$f \equiv g \iff c(f) = c(g)\ \ \text{(identical trees)}.$$
For polynomials with rational coefficients, such a form is the expansion with a fixed ordering of the monomials — checking an identity then
amounts to comparing two strings. For rational functions: numerator and denominator with no common divisor and a normalized denominator (cancel).
4. The limits. For expressions with transcendental functions there is, in general, no canonical form. Richardson (1968) showed that for expressions
built from rational numbers, $\pi$, $\ln 2$, the variable $x$, the operations $+,-,\cdot$, composition, and the functions $\sin$, $\exp$ and $|\cdot|$,
there is no algorithm that decides whether an expression is identically zero. That is why simplify in every CAS is a collection of heuristics,
not a guarantee.
x - y and x + (-1)*y with simplification turned on. Why does SymPy not need a separate “subtraction” node?2*(x+1) and then x*(x+1). Why do the parentheses “disappear” in the first case but not in the second?(x**2-1)/(x-1). It is not a polynomial, so our Expand button is disabled (SymPy would expand only the numerator: x**2/(x - 1) - 1/(x - 1)). Use Cancel common factors. Is the result x + 1 the same function as the input expression? (Hint: $x = 1$.)