Difference between revisions of "Python:Symbolic Computations"

From PrattWiki
Jump to navigation Jump to search
(Solving)
Line 23: Line 23:
  
 
== Solving ==
 
== Solving ==
* sim.solve() and sim.solveset()
+
* sym.solve() and sym.solveset()
* sim.dsolve()
+
* sym.dsolve()
  
 
== Interesting Things ==
 
== Interesting Things ==

Revision as of 11:25, 19 September 2022

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

  • sym.solve() and sym.solveset()
  • sym.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

Philosophical Things =

  • How to declare things? Knowns versus unknowns? All symbols and then all functions or batches of each?
  • Name equations or just number them?
  • When to solve after numbers are in versus before?
  • How much time to spend figuring out nice subscripts (probably less than already spent)?

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.