pianofisica

Mathematics & Physics, Maxima, a bit Python & Wolfram, and Arts

Python (SymPy) Programming for Symbolic Calculations (Basics)

Here I'd like to share how to use a Python library "SymPy", which is for symbolic formula manipulation.




How to use SymPy

In the following I'll show you concrete examples of input of Python (SymPy). Although I've checked them on JupyterNotebook, please let me know if you found any trouble. Copy, Paste and Run it (Shift + Enter)! Modify the input as you like! Let's get it started!

Import SymPy library

First of all, one must load SymPy library:

import sympy

Addition, Subtraction, Multiplication and Division

3 + 2 # letters after "#" is to be ignored for evaluation
3 - 2
3 * 2
sympy.Rational(3,2)

or

3 / 2

Modulo

11 % 2
11 // 2

Type of values

type( 3 )
type( 3. )

Power, Factorial, Double factorial, Square root

3 ** 2
3e2
3e-2
sympy.factorial(10)
sympy.factorial2(10)
sympy.factorial2(9)
sympy.sqrt(50)

Complex numbers

Imaginary unit
sympy.I**2   #  capital " I "
Complex conjugate
sympy.conjugate(2+3*sympy.I)



Real part, Imaginary part
sympy.re(2+sympy.I*3)
sympy.im(2+sympy.I*3)
Absolute value
sympy.Abs(2+sympy.I*3)
Argument
sympy.arg(2+sympy.I*3)

Mathematical constants

Pi
sympy.pi
Napier number
sympy.E
Euler's formula
sympy.E**( sympy.pi * sympy.I )
Infinity
sympy.oo

Refer numbers

sympy.pi.evalf(5)    # argument specifies how many digits you want to show

Algebraic manipulations

Prime factorization
sympy.factorint(sympy.factorial(10))
Declare variables
sympy.var('x')

or

x = sympy.symbols('x')
Factorization of polynomial
sympy.factor(x**2-4*x+3)
Partial fraction decomposition
sympy.apart(1/(x**2-4*x+3))
sympy.apart(1/(x**6-1))
Expand expression
sympy.var('x, y')
sympy.expand((x+y)**6)
Simplify expression
sympy.simplify((2*x-2)/((x-1)**2*(x-2)))
sympy.simplify(1/(x-1)**2+1/((x-1)*(x-2)))
Simplify and expand expression
sympy.cancel((2*x-2)/((x-1)**2*(x-2)))
sympy.cancel(1/(x-1)**2+1/((x-1)*(x-2)))
Examine True or False
0==sympy.sqrt(2)-2**(sympy.Rational(1,2))
0==sympy.sqrt(2)-2**(sympy.Rational(1,3))
sympy.factorial(50)==sympy.factorial2(50)*sympy.factorial2(49)

sometimes it needs some manipulation on expressions

x**2-2*x+1==(x-1)**2
x**2-2*x+1==sympy.expand((x-1)**2)
Extract a coefficient
( x**2-2*x+1 ).coeff(x, 2)
Substitution
sympy.var('x, a, b, c')
(a*x**2+b*x+c).subs(x, 3)
sympy.expand((a*x**2+b*x+c).subs(x, (-b + sympy.sqrt(-4*a*c + b**2))/(2*a)))

Declare the properties of variables

Integer
k = sympy.symbols('k',integer=True)
Real number
a, b = sympy.symbols('a, b', real=True)
sympy.conjugate(a+b*sympy.I)

unless declaring anything, SymPy regards variables as complex:

sympy.var('z')
sympy.conjugate(z)
Non-negative
sympy.var('r', nonnegative = True)
sympy.sqrt(r**2)
Positive
sympy.var('t', positive = True)
sympy.Abs(t)
Dependency
from sympy.core.function import Function
R = Function('R')(r, t)
sympy.diff(R, r)

Summation

k = sympy.symbols('k',integer=True)
sympy.summation(k, (k, 1, 10) )
k, N = sympy.symbols('k N',integer=True)
sympy.factor(sympy.summation(k, (k, 1, N) ))
sympy.factor(sympy.summation(k**3, (k, 1, N) ))

Multiple products

k = sympy.symbols('k',integer=True)
sympy.product( k, (k, 1, 10) )
sympy.factorial(10)==sympy.product(k, (k, 1, 10) )

Elementary functions

Trigonometric functions
sympy.sin(x)
sympy.cos(x)
sympy.tan(x)
sympy.sec(x)
sympy.csc(x)
sympy.cot(x)
Inverse trigonometric functions
sympy.asin(x)
sympy.acos(x)
sympy.atan(x)
Hyperbolic functions
sympy.sinh(x)
sympy.cosh(x)
sympy.tanh(x)
Exponential function
sympy.exp(x)
sympy.var('theta', real = True)
sympy.re(sympy.exp(sympy.I*theta)) 
Logarithmic function
sympy.log(x)

Manipulations over trigonometric/hyperbolic functions

Expansions
sympy.var('a, b')
sympy.expand(sympy.sin(a+b), trig=True)
Simplifications
sympy.trigsimp((sympy.sinh(a))**2+(sympy.cosh(a))**2)

Equation

Solve simultaneous equations
sympy.var('x, y')
sympy.solve ([3*x+4*y-5, 2*x+3*y-3], [x, y])
Find roots of algebraic equation
sympy.var('x, a, b, c')
sympy.solve (a*x**2+b*x+c, x)

For more details, see

pianofisica.hatenablog.com


Function

Assign expressions to a letter, and evaluate it at a value
sympy.var('x, y')
u=x+y
v=(x+y)**3
u.subs(x,5)
(v.subs(x,5)).subs(y,3)
Use assigned letter: 4 operations
u+v
sympy.expand(u+v)
sympy.factor(u+v)
sympy.expand(u*v)
sympy.simplify(u/v)
Use assigned letter: differentiation
sympy.diff(v, x)
sympy.diff(v, y, 2)

or

v.diff(y, 2)
0==sympy.diff(v, x, 1)-sympy.diff(v, x)
Use assigned letter: Integration
sympy.integrate(u, x)
sympy.integrate(v, (x, 0, 6))
Define a function
sympy.var('x')
def f(x):
    return sympy.log(1+x)/x
f(1)
Differentiation
sympy.diff(f(x), x, 1)
Integration
sympy.integrate(f(x), x)
Taylor expansion
sympy.series(f(x), x, 0, 7) 
Extract RHS, LHS, Denominator, Numerator
sympy.var('x')
F=x+1
G=x**2+x-2
E=sympy.Eq(x+1, F/G)
sympy.solve(E, x)
E.rhs
E.lhs
sympy.denom(E.rhs)
sympy.numer(E.rhs)

Limit / Improper integral

Limit
sympy.limit( sympy.sin(x)/x, x, 0 )
Improper integral
sympy.integrate(1/(sympy.sqrt(sympy.pi))*sympy.exp(-x**2), (x, -sympy.oo, sympy.oo) )

Matrices

Input matrices
sympy.var('a11, a12, a21, a22, b11, b12, b21, b22')
A = sympy.Matrix([
[a11,a12],
[a21,a22]])
B = sympy.Matrix([
[b11,b12],
[b21,b22]])
Refer the element
A[0,1]
Linear combination
sympy.var('c, d')
c * A + d * B
Matrix products
A * B
Power of matrices
A ** 3
Determinant
A.det()
Inverse matrix
A ** (-1)

For more details, see

pianofisica.hatenablog.com


Ordinary differential equations

sympy.var('a, x')
y = sympy.Function('y')(x)
eq = sympy.Eq( sympy.diff(y, x),  -a*y )
sympy.dsolve(eq)

For more details, see

pianofisica.hatenablog.com


Fourier analysis

pianofisica.hatenablog.com

Lists

Make List, Refer its element
S=list([1, 10, 100])
S[0]
S[0]+S[1]*S[2]
S[3]
Summation over all elements in a list
sum(S)
Min/Max elements in a list
min(S)
max(S)
Number of elements in a list
len(S)

FOR

def f(k):
    return k**2
List = []
for n in range(10):
    element = f(n)
    List.append(element)
print(List)

Display in TeX form

sympy.var('a, b, c, x')
E2=sympy.Eq(a*x**2+b*x+c, 0)
sol=sympy.solve(E2, x)
display(sol[1])
sympy.init_printing()
display(sol[1])

Output in TeX form

sympy.var('a, b, c, x')
E2=sympy.Eq(a*x**2+b*x+c, 0)
sol=sympy.solve(E2, x)
display(sol[1])
print(sympy.latex(sol[0]))

Output in SymPy source

sympy.var('x, y')
exp1 = sympy.log((1+x)*(1+y)**2)
exp2 = sympy.expand(exp1)
sympy.print_python( exp2 )

Initialize a letter

del(x)

Initialize all vriables

%reset





As we've seen so far, many objects in SymPy are associated with " sympy. "
we can shorten it by doing from the beginning

from sympy import sp

then, for example

sp.I**2


Keywords: Python, SymPy, JupyterNotbook

プライバシーポリシー