s Dotlink – A Sympy Tutorial by Andrey Grozin (Repost)

# link..link Point Curry Disco Visual Search Engine! # A Sympy Tutorial by Andrey Grozin (Repost)

Posted on Wed 29 June 2016 in misc

### SymPy¶

SymPy is a package for symbolic calculations in python, similar to Mathematica. It works with expressions containing symbols.

In :
from sympy import *
init_printing()


Symbols are basic bricks used to construct expressions. Each symbol has a name used for printing expressions. Objects of the class Symbol should be created and assigned to python variables in order to be used in expressions. The symbol name and the name of the variable to which this symbol is assigned are two independent things, and one may write abc=Symbol('xyz'). But then one has to write abc in input expressions, while SymPy will write xyz in output ones, producing unnecessary confusion. The python variable name should better be the same as the symbol name.

In languages specifically designed for symbolic calculations, such as Mathematica, if a variable to which nothing has been assigned is used, it automatically means a symbol with the same name. Python has not been designed for symbolic calculations. If you use a variable to which nothing has been assigned, you will get an error message. Symbol objects have to be created explicitly.

In :
x=Symbol('x')
a=x**2-1
a

Out:
$$x^{2} - 1$$

Several symbols can be defined at once. The string is split at spaces.

In :
y,z=symbols('y z')


Let's substitute $y+1$ for $x$.

In :
a.subs(x,y+1)

Out:
$$\left(y + 1\right)^{2} - 1$$

### Polynomials and rational functions¶

SymPy does not expand brackets automatically. The function expand is used for this.

In :
a=(x+y-z)**2
a

Out:
$$\left(x + y - z\right)^{2}$$
In :
a=expand(a)
a

Out:
$$x^{2} + 2 x y - 2 x z + y^{2} - 2 y z + z^{2}$$

Degree of the polynomial $a$ in $x$.

In :
degree(a,x)

Out:
$$2$$

Let's collect terms with same power of $x$ together.

In :
collect(a,x)

Out:
$$x^{2} + x \left(2 y - 2 z\right) + y^{2} - 2 y z + z^{2}$$

Any polynomial with integer coefficients can be factorized into polynomials with integer coefficients (which cannot be factorized further). There exist efficient algorithms to do this.

In :
a=factor(a)
a

Out:
$$\left(x + y - z\right)^{2}$$

SymPy does not automatically cancel ratios of polynomials by their greatest common divisor. The function cancel is used for this.

In :
a=(x**3-y**3)/(x**2-y**2)
a

Out:
$$\frac{x^{3} - y^{3}}{x^{2} - y^{2}}$$
In :
cancel(a)

Out:
$$\frac{x^{2} + x y + y^{2}}{x + y}$$

SymPy does not automatically bring sums of rational expressions to common denominator. The function together is used for this.

In :
a=y/(x-y)+x/(x+y)
a

Out:
$$\frac{x}{x + y} + \frac{y}{x - y}$$
In :
together(a)

Out:
$$\frac{x \left(x - y\right) + y \left(x + y\right)}{\left(x - y\right) \left(x + y\right)}$$

The function simplify tries to rewrite an expression in a simplest form. This concept is not well defined (different forms may be considered simplest in different contexts), and there exists no algorithm for such simplification. The function simplify works heuristically, and it is not possible to guess in advance what simplifications it will try. It is very convenient in interactive sessions in order to check if it will succeed in rewriting an expression in some reasonably good form. But it is not desirable to use it in programs. There one should better use more specialized functions which perform well defined expression transformations.

In :
simplify(a)

Out:
$$\frac{x^{2} + y^{2}}{x^{2} - y^{2}}$$

Partial fraction decomposition with respect to $x$.

In :
apart(a,x)

Out:
$$- \frac{y}{x + y} + \frac{y}{x - y} + 1$$

Let's substitute some values for the symbols $x$ and $y$.

In :
a=a.subs({x:1,y:2})
a

Out:
$$- \frac{5}{3}$$

And how much is it numerically?

In :
a.n()

Out:
$$-1.66666666666667$$
In :
a.subs({x:1,y:2}) > a.subs({x:2,y:1})

Out:
$$\mathrm{False}$$

## Elementary functions¶

SymPy automatically applies simplifications of elementary functions which are correct everywhere.

In :
sin(-x)

Out:
$$- \sin{\left (x \right )}$$
In :
cos(pi/4),tan(5*pi/6)

Out:
$$\left ( \frac{\sqrt{2}}{2}, \quad - \frac{\sqrt{3}}{3}\right )$$

SymPy can work with floating point numbers having arbitrarily high precision. Here is $\pi$ with 30 significant digits.

In :
pi.n(30)

Out:
$$3.14159265358979323846264338328$$

E is the base of natural logarithms.

In :
log(1),log(E)

Out:
$$\left ( 0, \quad 1\right )$$
In :
exp(log(x)),log(exp(x))

Out:
$$\left ( x, \quad \log{\left (e^{x} \right )}\right )$$

Why not $x$? Try $x=2\pi i$.

In :
sqrt(0)

Out:
$$0$$
In :
sqrt(x)**4,sqrt(x**4)

Out:
$$\left ( x^{2}, \quad \sqrt{x^{4}}\right )$$

Why not $x^2$? Try $x=i$.

Symbols can have certain properties. E.g., they can be positive. Then SymPy can simplify square roots better.

In :
p,q=symbols('p q',positive=True)
sqrt(p**2)

Out:
$$p$$
In :
sqrt(12*x**2*y),sqrt(12*p**2*y)

Out:
$$\left ( 2 \sqrt{3} \sqrt{x^{2} y}, \quad 2 \sqrt{3} p \sqrt{y}\right )$$

Let the symbol $n$ be integer (I is the imaginary unit).

In :
n=Symbol('n',integer=True)
exp(2*pi*I*n)

Out:
$$e^{2 i \pi n}$$

The method rewrite tries to rewrite an expression in terms of a given function.

In :
cos(x).rewrite(exp),exp(I*x).rewrite(cos)

Out:
$$\left ( \frac{e^{i x}}{2} + \frac{1}{2} e^{- i x}, \quad i \sin{\left (x \right )} + \cos{\left (x \right )}\right )$$
In :
asin(x).rewrite(log)

Out:
$$- i \log{\left (i x + \sqrt{- x^{2} + 1} \right )}$$

The function trigsimp tries to rewrite a trigonometric expression in a simplest form. In programs it is better to use more specialized functions.

In :
trigsimp(2*sin(x)**2+3*cos(x)**2)

Out:
$$\cos^{2}{\left (x \right )} + 2$$

The function expand_trig expands sines and cosines of sums and multiple angles.

In :
expand_trig(sin(x-y)),expand_trig(sin(2*x))

Out:
$$\left ( \sin{\left (x \right )} \cos{\left (y \right )} - \sin{\left (y \right )} \cos{\left (x \right )}, \quad 2 \sin{\left (x \right )} \cos{\left (x \right )}\right )$$

The inverse transformation, rewriting products and powers of sines and cosines into expressions linear in these functions, is needed more often. Suppose we work with a truncated Fourier series.

In :
a1,a2,b1,b2=symbols('a1 a2 b1 b2')
a=a1*cos(x)+a2*cos(2*x)+b1*sin(x)+b2*sin(2*x)
a

Out:
$$a_{1} \cos{\left (x \right )} + a_{2} \cos{\left (2 x \right )} + b_{1} \sin{\left (x \right )} + b_{2} \sin{\left (2 x \right )}$$

We want to square it and get a truncated Fourier series again.

In :
a**2

Out:
$$\left(a_{1} \cos{\left (x \right )} + a_{2} \cos{\left (2 x \right )} + b_{1} \sin{\left (x \right )} + b_{2} \sin{\left (2 x \right )}\right)^{2}$$
In :
a.subs({a1:1,a2:0,b1:0,b2:1})

Out:
$$\sin{\left (2 x \right )} + \cos{\left (x \right )}$$
In :
a.subs({a1:1,a2:0,b1:0,b2:1}).rewrite(exp)

Out:
$$- \frac{i}{2} \left(e^{2 i x} - e^{- 2 i x}\right) + \frac{e^{i x}}{2} + \frac{1}{2} e^{- i x}$$
In :
a.subs({a1:1,a2:0,b1:0,b2:1}).rewrite(exp).expand()

Out:
$$- \frac{i}{2} e^{2 i x} + \frac{e^{i x}}{2} + \frac{1}{2} e^{- i x} + \frac{i}{2} e^{- 2 i x}$$
In :
a.subs({a1:1,a2:0,b1:0,b2:1}).rewrite(exp).expand().rewrite(cos)

Out:
$$\frac{i}{2} \left(- i \sin{\left (2 x \right )} + \cos{\left (2 x \right )}\right) - \frac{i}{2} \left(i \sin{\left (2 x \right )} + \cos{\left (2 x \right )}\right) + \cos{\left (x \right )}$$
In :
p = a.subs({a1:1,a2:0,b1:0,b2:1}).rewrite(exp).expand().rewrite(cos)
p.expand()

Out:
$$\sin{\left (2 x \right )} + \cos{\left (x \right )}$$
In :
p.collect([cos(x),cos(2*x),cos(3*x),sin(x),sin(2*x),sin(3*x)])

Out:
$$\frac{i}{2} \left(- i \sin{\left (2 x \right )} + \cos{\left (2 x \right )}\right) - \frac{i}{2} \left(i \sin{\left (2 x \right )} + \cos{\left (2 x \right )}\right) + \cos{\left (x \right )}$$