180 likes | 460 Views
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)). Substitution. expr = cos(x) + 1 expr.subs(x,y) expr.subs(x,0) expr = x**y expr = expr.subs(y,x**y)
E N D
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))
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)
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)
sympify and evalf simpify('x**2+2*x+4') expr = sqrt(8) expr.evalf() pi.evalf(100)
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))
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)
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)
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)
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)
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..
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)