SymPy symbolic Python library demo: symbolically solving math and integrals & pretty-printing the output
From @Autoplectic:
sympy is exactly what you're looking for.
While I have a tendency to write some of the longest answers on Stack Overflow, that is the shortest answer I've seen on Stack Overflow.
Let's add a basic demo.
References and tutorials you'll need:
- https://www.sympy.org/en/index.html --> click "Get started with the tutorial"
- Tutorial index: https://docs.sympy.org/latest/tutorial/index.html Example pages:
- Basic Operations
- Printing
- Simplification
- Calculus
Calculus demo I came up with (see here for the main tutorial I looked at to get started):
Short version:
#!/usr/bin/env python3
from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)
integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
print(pretty(integral))
result = integral.doit() # "do it": evaluate the integral
print(pretty(result))
Longer version:
eRCaGuy_hello_world/math/sympy_integral_and_printing.py:
#!/usr/bin/env python3
from sympy import *
x, y, z = symbols('x y z')
init_printing(use_unicode=True)
# Store an integral
integral = Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
# print it in various ways
print("ORIGINAL INTEGRAL:")
print(pretty(integral))
pprint(integral) # "pretty print": same as above
print(pretty(integral, use_unicode=False)) # pretty print with ASCII instead
# of unicode
print(integral) # plain text
print(latex(integral)) # in LaTeX format
# Now solve the integral and output the result by telling it to
# "do it".
result = integral.doit()
# print it in various ways
print("\nRESULT:")
print(pretty(result))
pprint(result)
print(pretty(result, use_unicode=False))
print(result)
print(latex(result))
Note that using pprint(integral)
is the same as print(pretty(integral))
.
Output of running the above commands:
ORIGINAL INTEGRAL:
∞ ∞
⌠ ⌠
⎮ ⎮ 2 2
⎮ ⎮ - x - y
⎮ ⎮ ℯ dx dy
⌡ ⌡
-∞ -∞
∞ ∞
⌠ ⌠
⎮ ⎮ 2 2
⎮ ⎮ - x - y
⎮ ⎮ ℯ dx dy
⌡ ⌡
-∞ -∞
oo oo
/ /
| |
| | 2 2
| | - x - y
| | e dx dy
| |
/ /
-oo -oo
Integral(exp(-x**2 - y**2), (x, -oo, oo), (y, -oo, oo))
\int\limits_{-\infty}^{\infty}\int\limits_{-\infty}^{\infty} e^{- x^{2} - y^{2}}\, dx\, dy
RESULT:
π
π
pi
pi
\pi
The SymPy symbolic math library in Python can do pretty much any kind of math, solving equations, simplifying, factoring, substituting values for variables, pretty printing, converting to LaTeX format, etc. etc. It seems to be a pretty robust solver in my very limited use so far. I recommend trying it out.
Installing it, for me (tested on Linux Ubuntu), was as simple as:
pip3 install sympy