{"nbformat": 3, "metadata": {"name": "", "signature": "sha256:d52f00575a0c306379b7baef311cde05bd02eb399c2189761e937595d0e7fde0"}, "nbformat_minor": 0, "worksheets": [{"metadata": {}, "cells": [{"cell_type": "markdown", "source": ["# Choice of Nodes for Polynomial Interpolation"], "metadata": {}}, {"cell_type": "code", "language": "python", "outputs": [], "input": ["%matplotlib qt"], "metadata": {}, "collapsed": false, "prompt_number": 13}, {"cell_type": "code", "language": "python", "outputs": [], "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)"], "metadata": {}, "collapsed": false, "prompt_number": 14}, {"cell_type": "markdown", "source": ["Choose a function below:"], "metadata": {}}, {"cell_type": "code", "language": "python", "outputs": [], "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)"], "metadata": {}, "collapsed": false, "prompt_number": 10}, {"cell_type": "markdown", "source": ["Run this cell to play with the node placement toy:"], "metadata": {}}, {"cell_type": "code", "language": "python", "outputs": [], "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()"], "metadata": {}, "collapsed": false, "prompt_number": 12}]}]}