{ "metadata": { "name": "An-Introduction-to-NumPy-Basics" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "%pylab inline" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# This function appears to be written for scalar values only.\n", "\n", "def f(x):\n", " return 3 * x * x - 1\n", "\n", "print f(-1.0)\n", "print f(0.0)\n", "print f(1.0)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# But thanks to NumPy it can operate on arrays as well!\n", "\n", "import numpy as np\n", "\n", "x = np.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0])\n", "print f(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Graphing the result.\n", "\n", "import pylab as pl\n", "plot = pl.figure().add_subplot(111)\n", "plot.plot(x, f(x))\n", "plot.grid()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Use linspace() to make lots of x values for a smoother plot.\n", "\n", "x = linspace(-3.0, 3.0, 200)\n", "\n", "plot = pl.figure().add_subplot(111)\n", "plot.plot(x, f(x))\n", "plot.grid()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# What if we start with data and want the parabola?\n", "# We can use optimize() to fit a curve to noisy data.\n", "\n", "x = numpy.array([-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0])\n", "y = numpy.array([10.3, 5.1, 0.9, 3.6, 8.4, 16.3, 32.7])\n", "\n", "def parabola(x, a, b, c):\n", " return a*x*x + b*x + c\n", "\n", "from scipy.optimize import curve_fit\n", "(a, b, c), pcov = curve_fit(parabola, x, y)\n", "\n", "print a, b, c" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Here is the curve that optimize() figured out,\n", "# plotted next to the points we used for input.\n", "\n", "plot = pl.figure().add_subplot(111)\n", "plot.scatter(x, y)\n", "plot.plot(x, parabola(x, a, b, c))" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }