Skip to content

Instantly share code, notes, and snippets.

@sahilshekhawat
Created January 4, 2015 16:26
Show Gist options
  • Save sahilshekhawat/b6a506e051b909e6131a to your computer and use it in GitHub Desktop.
Save sahilshekhawat/b6a506e051b909e6131a to your computer and use it in GitHub Desktop.
(500) Internal Server Error while converting IPython Notebook to Python
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from IPython.display import display\n",
"\n",
"from sympy.interactive import printing\n",
"printing.init_printing(use_latex='mathjax')\n",
"\n",
"from __future__ import division\n",
"import sympy as sym\n",
"from sympy import *\n",
"x, y, z = symbols(\"x y z\")\n",
"k, m, n = symbols(\"k m n\", integer=True)\n",
"f, g, h = map(Function, 'fgh')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/latex": [
"$$\\frac{3 \\pi}{2} + \\frac{e^{i x}}{x^{2} + y}$$"
],
"text/plain": [
" ⅈ⋅x \n",
"3⋅π ℯ \n",
"─── + ──────\n",
" 2 2 \n",
" x + y"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Rational(3,2)*pi + exp(I*x) / (x**2 + y)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"def plot_taylor_approximations(func, x0=None, orders=(2, 4), xrange=(0,1), yrange=None, npts=200):\n",
" \"\"\"Plot the Taylor series approximations to a function at various orders.\n",
"\n",
" Parameters\n",
" ----------\n",
" func : a sympy function\n",
" x0 : float\n",
" Origin of the Taylor series expansion. If not given, x0=xrange[0].\n",
" orders : list\n",
" List of integers with the orders of Taylor series to show. Default is (2, 4).\n",
" xrange : 2-tuple or array.\n",
" Either an (xmin, xmax) tuple indicating the x range for the plot (default is (0, 1)),\n",
" or the actual array of values to use.\n",
" yrange : 2-tuple\n",
" (ymin, ymax) tuple indicating the y range for the plot. If not given,\n",
" the full range of values will be automatically used. \n",
" npts : int\n",
" Number of points to sample the x range with. Default is 200.\n",
" \"\"\"\n",
" if not callable(func):\n",
" raise ValueError('func must be callable')\n",
" if isinstance(xrange, (list, tuple)):\n",
" x = np.linspace(float(xrange[0]), float(xrange[1]), npts)\n",
" else:\n",
" x = xrange\n",
" if x0 is None: x0 = x[0]\n",
" xs = sym.Symbol('x')\n",
" # Make a numpy-callable form of the original function for plotting\n",
" fx = func(xs)\n",
" f = sym.lambdify(xs, fx, modules=['numpy'])\n",
" # We could use latex(fx) instead of str(), but matploblib gets confused\n",
" # with some of the (valid) latex constructs sympy emits. So we play it safe.\n",
" plt.plot(x, f(x), label=str(fx), lw=2)\n",
" # Build the Taylor approximations, plotting as we go\n",
" apps = {}\n",
" for order in orders:\n",
" app = fx.series(xs, x0, n=order).removeO()\n",
" apps[order] = app\n",
" # Must be careful here: if the approximation is a constant, we can't\n",
" # blindly use lambdify as it won't do the right thing. In that case, \n",
" # evaluate the number as a float and fill the y array with that value.\n",
" if isinstance(app, sym.numbers.Number):\n",
" y = np.zeros_like(x)\n",
" y.fill(app.evalf())\n",
" else:\n",
" fa = sym.lambdify(xs, app, modules=['numpy'])\n",
" y = fa(x)\n",
" tex = sym.latex(app).replace('$', '')\n",
" plt.plot(x, y, label=r'$n=%s:\\, %s$' % (order, tex) )\n",
" \n",
" # Plot refinements\n",
" if yrange is not None:\n",
" plt.ylim(*yrange)\n",
" plt.grid()\n",
" plt.legend(loc='best').get_frame().set_alpha(0.8)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.figure.Figure at 0x7fccbfc00ad0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"%matplotlib inline\n",
"plot_taylor_approximations(sin, 0, [2, 4, 6], (0, 2*pi), (-2,2))"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.8"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment