##// END OF EJS Templates
str(CapturedIO) gives stdout
str(CapturedIO) gives stdout

File last commit:

r6035:3077781f
r7410:511326e1
Show More
sympy.ipynb
625 lines | 113.3 KiB | text/plain | TextLexer

SymPy: Open Source Symbolic MathematicsĀ¶

This notebook uses the SymPy package to perform symbolic manipulations, and combined with numpy and matplotlib, also displays numerical visualizations of symbolically constructed expressions.

We first load sympy printing and plotting support, as well as all of sympy:

InĀ [1]:
%load_ext sympyprinting
%pylab inline

from __future__ import division
import sympy as sym
from sympy import *
x, y, z = symbols("x y z")
k, m, n = symbols("k m n", integer=True)
f, g, h = map(Function, 'fgh')
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline].
For more information, type 'help(pylab)'.

Elementary operations

InĀ [2]:
Rational(3,2)*pi + exp(I*x) / (x**2 + y)
Out[2]:
$$\frac{3}{2} \pi + \frac{e^{\mathbf{\imath} x}}{x^{2} + y}$$
InĀ [4]:
exp(I*x).subs(x,pi).evalf()
Out[4]:
$$-1.0$$
InĀ [5]:
e = x + 2*y
InĀ [6]:
srepr(e)
Out[6]:
Add(Symbol('x'), Mul(Integer(2), Symbol('y')))
InĀ [7]:
exp(pi * sqrt(163)).evalf(50)
Out[7]:
$$262537412640768743.99999999999925007259719818568888$$

Algebra

InĀ [8]:
eq = ((x+y)**2 * (x+1))
eq
Out[8]:
$$\left(x + 1\right) \left(x + y\right)^{2}$$
InĀ [9]:
expand(eq)
Out[9]:
$$x^{3} + 2 x^{2} y + x^{2} + x y^{2} + 2 x y + y^{2}$$
InĀ [10]:
a = 1/x + (x*sin(x) - 1)/x
a
Out[10]:
$$\frac{x \operatorname{sin}\left(x\right) -1}{x} + \frac{1}{x}$$
InĀ [11]:
simplify(a)
Out[11]:
$$\operatorname{sin}\left(x\right)$$
InĀ [12]:
eq = Eq(x**3 + 2*x**2 + 4*x + 8, 0)
eq
Out[12]:
$$x^{3} + 2 x^{2} + 4 x + 8 = 0$$
InĀ [13]:
solve(eq, x)
Out[13]:
[-2, -2ā‹…ā…ˆ, 2ā‹…ā…ˆ]
InĀ [14]:
a, b = symbols('a b')
Sum(6*n**2 + 2**n, (n, a, b))
Out[14]:
$$\sum_{n=a}^{b} \left(2^{n} + 6 n^{2}\right)$$

Calculus

InĀ [15]:
limit((sin(x)-x)/x**3, x, 0)
Out[15]:
$$- \frac{1}{6}$$
InĀ [16]:
(1/cos(x)).series(x, 0, 6)
Out[16]:
$$1 + \frac{1}{2} x^{2} + \frac{5}{24} x^{4} + \operatorname{\mathcal{O}}\left(x^{6}\right)$$
InĀ [17]:
diff(cos(x**2)**2 / (1+x), x)
Out[17]:
$$- 4 \frac{x \operatorname{sin}\left(x^{2}\right) \operatorname{cos}\left(x^{2}\right)}{x + 1} - \frac{\operatorname{cos}^{2}\left(x^{2}\right)}{\left(x + 1\right)^{2}}$$
InĀ [18]:
integrate(x**2 * cos(x), (x, 0, pi/2))
Out[18]:
$$-2 + \frac{1}{4} \pi^{2}$$
InĀ [19]:
eqn = Eq(Derivative(f(x),x,x) + 9*f(x), 1)
display(eqn)
dsolve(eqn, f(x))
$$9 \operatorname{f}\left(x\right) + \frac{\partial^{2}}{\partial^{2} x} \operatorname{f}\left(x\right) = 1$$
Out[19]:
$$\operatorname{f}\left(x\right) = C_{1} \operatorname{sin}\left(3 x\right) + C_{2} \operatorname{cos}\left(3 x\right) + \frac{1}{9}$$

Illustrating Taylor seriesĀ¶

We will define a function to compute the Taylor series expansions of a symbolically defined expression at various orders and visualize all the approximations together with the original function

InĀ [20]:
# You can change the default figure size to be a bit larger if you want,
# uncomment the next line for that:
#plt.rc('figure', figsize=(10, 6))
InĀ [21]:
def plot_taylor_approximations(func, x0=None, orders=(2, 4), xrange=(0,1), yrange=None, npts=200):
    """Plot the Taylor series approximations to a function at various orders.

    Parameters
    ----------
    func : a sympy function
    x0 : float
      Origin of the Taylor series expansion.  If not given, x0=xrange[0].
    orders : list
      List of integers with the orders of Taylor series to show.  Default is (2, 4).
    xrange : 2-tuple or array.
      Either an (xmin, xmax) tuple indicating the x range for the plot (default is (0, 1)),
      or the actual array of values to use.
    yrange : 2-tuple
      (ymin, ymax) tuple indicating the y range for the plot.  If not given,
      the full range of values will be automatically used. 
    npts : int
      Number of points to sample the x range with.  Default is 200.
    """
    if not callable(func):
        raise ValueError('func must be callable')
    if isinstance(xrange, (list, tuple)):
        x = np.linspace(float(xrange[0]), float(xrange[1]), npts)
    else:
        x = xrange
    if x0 is None: x0 = x[0]
    xs = sym.Symbol('x')
    # Make a numpy-callable form of the original function for plotting
    fx = func(xs)
    f = sym.lambdify(xs, fx, modules=['numpy'])
    # We could use latex(fx) instead of str(), but matploblib gets confused
    # with some of the (valid) latex constructs sympy emits.  So we play it safe.
    plot(x, f(x), label=str(fx), lw=2)
    # Build the Taylor approximations, plotting as we go
    apps = {}
    for order in orders:
        app = fx.series(xs, x0, n=order).removeO()
        apps[order] = app
        # Must be careful here: if the approximation is a constant, we can't
        # blindly use lambdify as it won't do the right thing.  In that case, 
        # evaluate the number as a float and fill the y array with that value.
        if isinstance(app, sym.numbers.Number):
            y = np.zeros_like(x)
            y.fill(app.evalf())
        else:
            fa = sym.lambdify(xs, app, modules=['numpy'])
            y = fa(x)
        tex = sym.latex(app).replace('$', '')
        plot(x, y, label=r'$n=%s:\, %s$' % (order, tex) )
        
    # Plot refinements
    if yrange is not None:
        plt.ylim(*yrange)
    grid()
    legend(loc='best').get_frame().set_alpha(0.8)

With this function defined, we can now use it for any sympy function or expression

InĀ [22]:
plot_taylor_approximations(sin, 0, [2, 4, 6], (0, 2*pi), (-2,2))
No description has been provided for this image
InĀ [23]:
plot_taylor_approximations(cos, 0, [2, 4, 6], (0, 2*pi), (-2,2))
No description has been provided for this image

This shows easily how a Taylor series is useless beyond its convergence radius, illustrated by a simple function that has singularities on the real axis:

InĀ [24]:
# For an expression made from elementary functions, we must first make it into
# a callable function, the simplest way is to use the Python lambda construct.
plot_taylor_approximations(lambda x: 1/cos(x), 0, [2,4,6], (0, 2*pi), (-5,5))
No description has been provided for this image