12
SymPy A Symbolic Mathematics package in and for Python

SymPy A Symbolic Mathematics package in and for Python

Embed Size (px)

Citation preview

Page 1: SymPy A Symbolic Mathematics package in and for Python

SymPy

A Symbolic Mathematics packagein and for Python

Page 2: SymPy A Symbolic Mathematics package in and for Python

Getting Started

x,y = symbols('x y') a = 2*x + y a + y expand(a**3) factor(x**3+3*x**2+3*x+1) simplify(x**2-y**2-(x+y)*(x-y))

Page 3: SymPy A Symbolic Mathematics package in and for Python

Substitution

expr = cos(x) + 1

expr.subs(x,y)

expr.subs(x,0)

expr = x**y

expr = expr.subs(y,x**y)

(repeat a few times)

Page 4: SymPy A Symbolic Mathematics package in and for Python

Trigs

trigx = sin(2*x) + cos(2*x)

expand_trig(exprx)

trigsimp(cos(x)**2 + sin(x)**2)

Also for hyperbolic functions:

trigsimp(cosh(x)**2=sinh(x)**2)

Page 5: SymPy A Symbolic Mathematics package in and for Python

sympify and evalf

simpify('x**2+2*x+4')

expr = sqrt(8)

expr.evalf()

pi.evalf(100)

Page 6: SymPy A Symbolic Mathematics package in and for Python

simplification

What is simplification?

simplify((x**3 + x**2 -x -1)/(x**2 +2*x +1))

simplify((x**4 – 1)/(x - 1))

simplify((x**4 – 1)/(x**2 – 1))

expand((x+2*y)**3)

cancel((x**4 - 1)/(x – 1))

cancel((x**2 + 2* x + 1)/(x**2 - 1))

Page 7: SymPy A Symbolic Mathematics package in and for Python

Watch out for powers:

xp,yp = symbols('x y',positive=True)

a,b = symbols('a b', real=True)

powsimp(x**a*y**a)

powsimp(xp**a*yp**a)

Page 8: SymPy A Symbolic Mathematics package in and for Python

Exponentials and logarithms

ln(x)

expand_log(log(x*y))

expand_log(log(x/y))

expand_log(log(x**2))

expand_log(log(x**n))

expand_log(log(x**a))

logcombine undoes expand_log (if possible)

Page 9: SymPy A Symbolic Mathematics package in and for Python

Calculus

diff(expr,var,var,var,....)

integrate(expr,var)

or

integrate(expr,(var,low,high))

Can repeat variables (or limit tuples) as with diff.

For infinity, use oo

limit(expr,var,value)

Page 10: SymPy A Symbolic Mathematics package in and for Python

Equations

Equations represented by Eq, but any expression can implicitly be Eq to 0

solve(exprs,vars)

Note: not guaranteed (cfr Hilbert's 10th problem)

For a polynomial, use roots

roots(x**3 – 6*x**2 + 9*x,x)

Page 11: SymPy A Symbolic Mathematics package in and for Python

Matrices

Matrix([[1, 2],[3,4],[5,6]]) # rowwise

Matrix([1,2,3]) # is a column vector

Matrices are mutable (unlike other sympy objects)

Transpose:

M.T

eye(n) (n x n id matrix)

zeros(n,m) #n rows, m columns

ones(n,m)

diag(a,b,c,,,) #diagonal matrix, the args can also be matrices..

Page 12: SymPy A Symbolic Mathematics package in and for Python

Matrix methods:

M.det()

M.rref → reduced row echelon form, list of indices of pivot columns

M.nullspace

M.eigenvals (returns a dictionary of algebraic multiplicity pairs)

M.diagonalize → (P,D) such that D is diagonal, and M = P D P**(-1)