Python:Symbolic Computations

From PrattWiki
Revision as of 21:14, 18 December 2021 by DukeEgr93 (talk | contribs)
Jump to navigation Jump to search

This is a sandbox for information on symbolic computation with Python. It is about as organized as one might expect...

Preamble

  • This page will be consistent with Python:Nicknames in terms of module imports. Note that there are several ways to get the SymPy package into Python:
    • import sympy as sym (what this page does)
    • import sympy as sp (this is more consistent with bringing in NumPy, but that's what we will use for SciPy)
    • from sympy import * (if you are sure nothing in SymPy will contradict anything in built-in Python)
    • from sympy import TUPLE OF THINGS (if you just have a few specific things you want to do with SymPy)
  • sym.init_session() will automatically bring in x, y, z, and t as symbols; k, m, n as integers; f, g, h as function names; and sym.init_printing HOWEVER it brings in all of sympy with from sympy import *!

Defining Symbols

  • a, b, c = sym.symbols('a b c') or a, b, c = sym.symbols('a, b, c')
  • The symbolic representation can be entirely different from the variable with a, b, c = sym.symbols('let\'s go Duke')
  • If the symbolic and variable names exactly match more efficient to use sym.var('a b c') or sym.var('a, b, c')
    • May want to assign this to a variable or append a ; since this returns a tuple with the variables in it

Substitutions

  • use .subs(variable, value) or .subs(iterable) where iterable has a collection of variables and values

Output

  • To make output prettier: sym.init_printing()
  • Display depends on if LaTeX is installed or not

Solving

  • sim.solve() and sim.solveset()
  • sim.dsolve()

Interesting Things

  • sym.lambdify((variables), expression, "numpy") will return a function that performs the calculation in the expression
  • sym.simplify(expression) will work to simplify an expression
  • sym.Matrix() can have symbols and will calculate things symbolically

References

Future Work

  • Subscripts are...strange. Numbers coming at the end of a variable print as subscripts but letters end that behavior. One workaround is to define a variable with the xa = sym.Symbol('x_a') command but that will only take a single character superscript.