Intro to sympy variables in previous notebook.
import sympy as sym
sym.init_printing() # for LaTeX formatted output
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# Following is an Ipython magic command that puts figures in the notebook.
%matplotlib notebook
# M.L. modification of matplotlib defaults
# Changes can also be put in matplotlibrc file,
# or effected using mpl.rcParams[]
mpl.style.use('classic')
plt.rc('figure', figsize = (6, 4.5)) # Reduces overall size of figures
plt.rc('axes', labelsize=16, titlesize=14)
plt.rc('figure', autolayout = True) # Adjusts supblot parameters for new size
x = sym.symbols('x')
f, g = sym.symbols('f g', cls=sym.Function)
f(x)
diffeq = sym.Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sym.sin(x))
diffeq
soln = sym.dsolve(diffeq,f(x))
soln
This isn't implemented yet in dsolve
-- it's on the "to do" list
For now, solve for contants on your own. For example, if
$$ f(0) = 1\quad\mbox{and}\quad\left.\frac{df}{dx}\right|_0 = 0, $$
solve the following equations:
constants = sym.solve([soln.rhs.subs(x,0) - 1, soln.rhs.diff(x,1).subs(x,0)- 0])
constants
C1, C2 = sym.symbols('C1,C2')
soln = soln.subs(constants)
soln
I'm not sure why I had to specify the modulue for conversion of sympy functions.
See http://docs.sympy.org/latest/modules/utilities/lambdify.html
In previous examples, sympy figured out a good module "on its own."
func = sym.lambdify(x,soln.rhs,'numpy')
xx = np.linspace(-1,1,201) # name = xx so it won't collide with symbol x
y = func(xx)
plt.figure()
plt.xlabel('$x$')
plt.ylabel('$f(x)$')
plt.plot(xx,y);
version_information
is from J.R. Johansson (jrjohansson at gmail.com); see Introduction to scientific computing with Python for more information and instructions for package installation.
version_information
is installed on the linux network at Bucknell
%load_ext version_information
version_information sympy, numpy, matplotlib