{"nbformat": 3, "worksheets": [{"cells": [{"source": ["# Choice of Nodes for Polynomial Interpolation"], "cell_type": "markdown", "metadata": {}}, {"language": "python", "cell_type": "code", "input": ["%matplotlib qt"], "collapsed": false, "outputs": [], "prompt_number": 1, "metadata": {}}, {"language": "python", "cell_type": "code", "input": ["import numpy as np\n", "import numpy.linalg as la\n", "\n", "from matplotlib.pyplot import (\n", " clf, plot, show, xlim, ylim,\n", " get_current_fig_manager, gca, draw, connect)"], "collapsed": false, "outputs": [], "prompt_number": 14, "metadata": {}}, {"source": ["Choose a function below:"], "cell_type": "markdown", "metadata": {}}, {"language": "python", "cell_type": "code", "input": ["func = \"sin\"\n", "\n", "if func == \"sin\":\n", " def f(x):\n", " return np.sin(5*x)\n", "elif func == \"jump\":\n", " def f(x):\n", " result = 0*x\n", " result.fill(-1)\n", " result[x > 0] = 1\n", " return result\n", "elif func == \"runge\":\n", " def f(x):\n", " return 1/(1+25*x**2)\n", "else:\n", " raise RuntimeError(\"unknown function '%s'\" % func)"], "collapsed": false, "outputs": [], "prompt_number": 10, "metadata": {}}, {"source": ["Run this cell to play with the node placement toy:"], "cell_type": "markdown", "metadata": {}}, {"language": "python", "cell_type": "code", "input": ["x_points = []\n", "y_points = []\n", "deg = [1]\n", "\n", "def update_plot():\n", " clf()\n", " xlim([-1, 1])\n", " ylim([-1.5, 1.5])\n", " gca().set_autoscale_on(False)\n", " plot(x_points, y_points, 'o')\n", "\n", " x = np.linspace(-1, 1, 500)\n", " plot(x, f(x), \"--\")\n", "\n", " if len(x_points) >= deg[0]+1:\n", " eval_points = np.linspace(-1, 1, 500)\n", " poly = np.poly1d(np.polyfit(\n", " np.array(x_points),\n", " np.array(y_points), deg[0]))\n", " plot(eval_points, poly(eval_points), \"-\")\n", "\n", "\n", "def click(event):\n", " \"\"\"If the left mouse button is pressed: draw a little square. \"\"\"\n", " tb = get_current_fig_manager().toolbar\n", " if event.button == 1 and event.inaxes and tb.mode == '':\n", " x_points.append(event.xdata)\n", " x_ary = np.array([event.xdata])\n", " y_ary = f(x_ary)\n", " y_points.append(y_ary[0])\n", "\n", " if event.button == 2 and event.inaxes and tb.mode == '':\n", " if len(x_points) >= deg[0]+2:\n", " deg[0] += 1\n", "\n", " update_plot()\n", " draw()\n", "\n", "update_plot()\n", "connect('button_press_event', click)\n", "show()"], "collapsed": false, "outputs": [], "prompt_number": 12, "metadata": {}}], "metadata": {}}], "nbformat_minor": 0, "metadata": {"name": "", "signature": "sha256:d52f00575a0c306379b7baef311cde05bd02eb399c2189761e937595d0e7fde0"}}