## Symbolic math in python

| categories: | tags: | View Comments

Matlab post Python has capability to do symbolic math through the sympy package.

## 1 Solve the quadratic equation

from sympy import solve, symbols, pprint

a,b,c,x = symbols('a,b,c,x')

f = a*x**2 + b*x + c

solution = solve(f, x)
print solution
pprint(solution)

>>> >>> >>> >>> >>> >>> [(-b + (-4*a*c + b**2)**(1/2))/(2*a), -(b + (-4*a*c + b**2)**(1/2))/(2*a)]
_____________   /       _____________\
/           2    |      /           2 |
-b + \/  -4*a*c + b    -\b + \/  -4*a*c + b  /
[---------------------, -----------------------]
2*a                     2*a


The solution you should recognize in the form of $$\frac{b \pm \sqrt{b^2 - 4 a c}}{2 a}$$ although python does not print it this nicely!

## 2 differentiation

from sympy import diff

print diff(f, x)
print diff(f, x, 2)

print diff(f, a)

>>> 2*a*x + b
2*a
>>> x**2


## 3 integration

from sympy import integrate

print integrate(f, x)          # indefinite integral
print integrate(f, (x, 0, 1))  # definite integral from x=0..1

>>> a*x**3/3 + b*x**2/2 + c*x
a/3 + b/2 + c


## 4 Analytically solve a simple ODE

from sympy import Function, Symbol, dsolve
f = Function('f')
x = Symbol('x')
fprime = f(x).diff(x) - f(x) # f' = f(x)

y = dsolve(fprime, f(x))

print y
print y.subs(x,4)
print [y.subs(x, X) for X in [0, 0.5, 1]] # multiple values

>>> >>> >>> >>> >>> >>> f(x) == exp(C1 + x)
f(4) == exp(C1 + 4)
[f(0) == exp(C1), f(0.5) == exp(C1 + 0.5), f(1) == exp(C1 + 1)]


It is not clear you can solve the initial value problem to get C1.

The symbolic math in sympy is pretty good. It is not up to the capability of Maple or Mathematica, (but neither is Matlab) but it continues to be developed, and could be helpful in some situations.