SymPy - Symbolic Computation


Advertisements

Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python's math module as given below −

>>> import math 
>>> print (math.sqrt(25), math.sqrt(7))

The output for the above code snippet is as follows −

5.0 2.6457513110645907

As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below −

>>> import sympy 
>>> print (sympy.sqrt(7))

The output for the above code snippet is as follows −

sqrt(7)

It is possible to simplify and show result of expression symbolically with the code snippet below −

>>> import math
>>> print (math.sqrt(12))

The output for the above code snippet is as follows −

3.4641016151377544

You need to use the below code snippet to execute the same using sympy −

##sympy output 
>>> print (sympy.sqrt(12))

And the output for that is as follows −

2*sqrt(3)

SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet −

>>> from sympy import * 
>>> x=Symbol ('x') 
>>> expr = integrate(x**x, x) 
>>> expr

On executing the above command in python shell, following output will be generated −

Integral(x**x, x)

Which is equivalent to

$\int \mathrm{x}^{x}\,\mathrm{d}x$

The square root of a non-perfect square can be represented by Latex as follows using traditional symbol −

>>> from sympy import * 
>>> x=7 
>>> sqrt(x)

The output for the above code snippet is as follows −

$\sqrt7$

A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc.

Advertisements