Introduction - SymPy 1.13.0rc2 documentation (2024)

What is Symbolic Computation?

Symbolic computation deals with the computation of mathematical objectssymbolically. This means that the mathematical objects are representedexactly, not approximately, and mathematical expressions with unevaluatedvariables are left in symbolic form.

Let’s take an example. Say we wanted to use the built-in Python functions tocompute square roots. We might do something like this

>>> import math>>> math.sqrt(9)3.0

9 is a perfect square, so we got the exact answer, 3. But suppose we computedthe square root of a number that isn’t a perfect square

>>> math.sqrt(8)2.82842712475

Here we got an approximate result. 2.82842712475 is not the exact square rootof 8 (indeed, the actual square root of 8 cannot be represented by a finitedecimal, since it is an irrational number). If all we cared about was thedecimal form of the square root of 8, we would be done.

But suppose we want to go further. Recall that \(\sqrt{8} = \sqrt{4\cdot 2} =2\sqrt{2}\). We would have a hard time deducing this from the above result.This is where symbolic computation comes in. With a symbolic computationsystem like SymPy, square roots of numbers that are not perfect squares areleft unevaluated by default

>>> import sympy>>> sympy.sqrt(3)sqrt(3)

Furthermore—and this is where we start to see the real power of symboliccomputation—symbolic results can be symbolically simplified.

>>> sympy.sqrt(8)2*sqrt(2)

A More Interesting Example

The above example starts to show how we can manipulate irrational numbersexactly using SymPy. But it is much more powerful than that. Symboliccomputation systems (which by the way, are also often called computer algebrasystems, or just CASs) such as SymPy are capable of computing symbolicexpressions with variables.

As we will see later, in SymPy, variables are defined using symbols.Unlike many symbolic manipulation systems, variables in SymPy must be definedbefore they are used (the reason for this will be discussed in the nextsection).

Let us define a symbolic expression, representing the mathematical expression\(x + 2y\).

>>> from sympy import symbols>>> x, y = symbols('x y')>>> expr = x + 2*y>>> exprx + 2*y

Note that we wrote x + 2*y just as we would if x and y wereordinary Python variables. But in this case, instead of evaluating tosomething, the expression remains as just x + 2*y. Now let us play aroundwith it:

>>> expr + 1x + 2*y + 1>>> expr - x2*y

Notice something in the above example. When we typed expr - x, we did notget x + 2*y - x, but rather just 2*y. The x and the -xautomatically canceled one another. This is similar to how sqrt(8)automatically turned into 2*sqrt(2) above. This isn’t always the case inSymPy, however:

>>> x*exprx*(x + 2*y)

Here, we might have expected \(x(x + 2y)\) to transform into \(x^2 + 2xy\), butinstead we see that the expression was left alone. This is a common theme inSymPy. Aside from obvious simplifications like \(x - x = 0\) and \(\sqrt{8} =2\sqrt{2}\), most simplifications are not performed automatically. This isbecause we might prefer the factored form \(x(x + 2y)\), or we might prefer theexpanded form \(x^2 + 2xy\). Both forms are useful in different circ*mstances.In SymPy, there are functions to go from one form to the other

>>> from sympy import expand, factor>>> expanded_expr = expand(x*expr)>>> expanded_exprx**2 + 2*x*y>>> factor(expanded_expr)x*(x + 2*y)

The Power of Symbolic Computation

The real power of a symbolic computation system such as SymPy is the abilityto do all sorts of computations symbolically. SymPy can simplify expressions,compute derivatives, integrals, and limits, solve equations, work withmatrices, and much, much more, and do it all symbolically. It includesmodules for plotting, printing (like 2D pretty printed output of mathformulas, or \(\mathrm{\LaTeX}\)), code generation, physics, statistics, combinatorics,number theory, geometry, logic, and more. Here is a small sampling of the sortof symbolic power SymPy is capable of, to whet your appetite.

>>> from sympy import *>>> x, t, z, nu = symbols('x t z nu')

This will make all further examples pretty print with unicode characters.

Take the derivative of \(\sin{(x)}e^x\).

>>> diff(sin(x)*exp(x), x) x xℯ ⋅sin(x) + ℯ ⋅cos(x)

Compute \(\int(e^x\sin{(x)} + e^x\cos{(x)})\,dx\).

>>> integrate(exp(x)*sin(x) + exp(x)*cos(x), x) xℯ ⋅sin(x)

Compute \(\int_{-\infty}^\infty \sin{(x^2)}\,dx\).

>>> integrate(sin(x**2), (x, -oo, oo))√2⋅√π───── 2

Find \(\lim_{x\to 0}\frac{\sin{(x)}}{x}\).

>>> limit(sin(x)/x, x, 0)1

Solve \(x^2 - 2 = 0\).

>>> solve(x**2 - 2, x)[-√2, √2]

Solve the differential equation \(y'' - y = e^t\).

>>> y = Function('y')>>> dsolve(Eq(y(t).diff(t, t) - y(t), exp(t)), y(t)) -t ⎛ t⎞ ty(t) = C₂⋅ℯ + ⎜C₁ + ─⎟⋅ℯ ⎝ 2⎠

Find the eigenvalues of \(\left[\begin{smallmatrix}1 & 2\\2 &2\end{smallmatrix}\right]\).

>>> Matrix([[1, 2], [2, 2]]).eigenvals()⎧3 √17 3 √17 ⎫⎨─ - ───: 1, ─ + ───: 1⎬⎩2 2 2 2 ⎭

Rewrite the Bessel function \(J_{\nu}\left(z\right)\) in terms of thespherical Bessel function \(j_\nu(z)\).

>>> besselj(nu, z).rewrite(jn)√2⋅√z⋅jn(ν - 1/2, z)──────────────────── √π

Print \(\int_{0}^{\pi} \cos^{2}{\left (x \right )}\, dx\) using \(\mathrm{\LaTeX}\).

>>> latex(Integral(cos(x)**2, (x, 0, pi)))\int\limits_{0}^{\pi} \cos^{2}{\left(x \right)}\, dx

Why SymPy?

There are many computer algebra systems out there. This Wikipediaarticle lists many of them. What makes SymPy a better choice than thealternatives?

First off, SymPy is completely free. It is open source, and licensed under theliberal BSD license, so you can modify the source code and even sell it if youwant to. This contrasts with popular commercial systems like Maple orMathematica that cost hundreds of dollars in licenses.

Second, SymPy uses Python. Most computer algebra systems invent their ownlanguage. Not SymPy. SymPy is written entirely in Python, and is executedentirely in Python. This means that if you already know Python, it is mucheasier to get started with SymPy, because you already know the syntax (and ifyou don’t know Python, it is really easy to learn). We already know thatPython is a well-designed, battle-tested language. The SymPy developers areconfident in their abilities in writing mathematical software, but programminglanguage design is a completely different thing. By reusing an existinglanguage, we are able to focus on those things that matter: the mathematics.

Another computer algebra system, Sage also uses Python as its language. ButSage is large, with a download of over a gigabyte. An advantage of SymPy isthat it is lightweight. In addition to being relatively small, it has nodependencies other than Python, so it can be used almost anywhere easily.Furthermore, the goals of Sage and the goals of SymPy are different. Sageaims to be a full featured system for mathematics, and aims to do so bycompiling all the major open source mathematical systems together intoone. When you call some function in Sage, such as integrate, it calls outto one of the open source packages that it includes. In fact, SymPy isincluded in Sage. SymPy on the other hand aims to be an independent system,with all the features implemented in SymPy itself.

A final important feature of SymPy is that it can be used as a library. Manycomputer algebra systems focus on being usable in interactive environments, butif you wish to automate or extend them, it is difficult to do. With SymPy,you can just as easily use it in an interactive Python environment or importit in your own Python application. SymPy also provides APIs to make it easyto extend it with your own custom functions.

Introduction - SymPy 1.13.0rc2 documentation (2024)
Top Articles
Latest Posts
Article information

Author: Msgr. Benton Quitzon

Last Updated:

Views: 5824

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Msgr. Benton Quitzon

Birthday: 2001-08-13

Address: 96487 Kris Cliff, Teresiafurt, WI 95201

Phone: +9418513585781

Job: Senior Designer

Hobby: Calligraphy, Rowing, Vacation, Geocaching, Web surfing, Electronics, Electronics

Introduction: My name is Msgr. Benton Quitzon, I am a comfortable, charming, thankful, happy, adventurous, handsome, precious person who loves writing and wants to share my knowledge and understanding with you.