{ "metadata": { "name": "", "signature": "sha256:1e91ae23276c1bb391bfeeeebba60e09fe692febff9eff87c7994dab3f8acc2e" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 1 - Basic iPython Tutorial (EE 126 Fall 2014)\n", "\n", "modified from Berkeley Python Bootcamp 2013 https://github.com/profjsb/python-bootcamp\n", "\n", "and Python for Signal Processing http://link.springer.com/book/10.1007%2F978-3-319-01342-8\n", "\n", "and EE 123 iPython Tutorial http://inst.eecs.berkeley.edu/~ee123/sp14/lab/python_tutorial.ipynb\n", "\n", "\\- Rishi Sharma" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## General iPython Notebook usage instructions (overview)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Click the `Play` button to run and advance a cell. The short-cut for it is `shift-enter`\n", "- To add a new cell, either select `\"Insert->Insert New Cell Below\"` or click the white down arrow button\n", "- You can change the cell mode from code to text in the pulldown menu. I use `Markdown` for text\n", "- You can change the texts in the `Markdown` cells by double-clicking them.\n", "- To save your notebook, either select `\"File->Save and Checkpoint\"` or hit `Command-s` for Mac and `Ctrl-s` for Windows\n", "- To undo in each cell, hit `Command-z` for Mac and `Ctrl-z` for Windows\n", "- To undo `Delete Cell`, select `Edit->Undo Delete Cell`\n", "- `Help->Keyboard Shortcuts` has a list of keyboard shortcuts" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Installing Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Follow the instructions on the class website to install python (if you're reading this, you've probably already done that):\n", "\n", "http://ipython.org/install.html\n", "\n", "Make sure you install the notebook dependencies for iPython in addition to the basic package" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tab Completion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One useful feature of iPython is tab completion " ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1\n", "y = 2\n", "x_plus_y = x+y\n", "\n", "# type `x_` then hit TAB will auto-complete the variable\n", "# then press shift + enter to run the cell\n", "print x_\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Help" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another useful feature is the help command. Type any function followed by `?` and run the cell returns a help window. Hit the `x` button to close it." ] }, { "cell_type": "code", "collapsed": false, "input": [ "abs?" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hit `Tab` after a left parenthesis also brings up a help window. Press Tab twice to see a more detailed Help window. Press Tab four times to have the same help window pop up that does if you use `?`. Some people may need to use `Shift+Tab` rather than just `Tab`. You can also just wait a few seconds after typing a left parenthesis and a help window will appear." ] }, { "cell_type": "code", "collapsed": false, "input": [ "abs(" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Floats and Integers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Doing math in python is easy, but note that there are `int` and `float` in Python. Integer division returns the floor. Always check this when debugging!" ] }, { "cell_type": "code", "collapsed": true, "input": [ "59 / 87" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "59 / 87.0" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, this will change in the future (Python 3.0)... If you import division from the future, then everything works fine" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from __future__ import division\n", "59 / 87" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Double quotes and single quotes are the same thing. `'+'` concatenates strings" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# This is a comment\n", "\"Hi \" + 'Bye'" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A list is a mutable array of data, ie can change stuff. They can be created using square brackets [ ]\n", "\n", "\n", "Important functions: \n", "\n", "- `'+'` appends lists. \n", "\n", "- `len(x)` to get length" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = [1, 2, \"asdf\"] + [4, 5, 6]\n", "\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print len(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A tuple is an unmutable list. They can be created using round brackets (). \n", "\n", "They are usually used as inputs and outputs to functions" ] }, { "cell_type": "code", "collapsed": false, "input": [ "t = (1, 2, \"asdf\") + (3, 4, 5)\n", "print t" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# cannot do assignment\n", "t[0] = 10\n", "\n", "# errors in ipython notebook appear inline" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arrays (Numpy)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy array is like a list with multidimensional support and more functions. We will be using it a lot.\n", "\n", "Arithmetic operations on numpy arrays correspond to elementwise operations. \n", "\n", "Important functions:\n", "\n", "- `.shape` returns the dimensions of the array\n", "\n", "- `.ndim` returns the number of dimensions. \n", "\n", "- `.size` returns the number of entries in the array\n", "\n", "- `len()` returns the first dimension\n", "\n", "\n", "To use functions in numpy, we have to import numpy to our workspace. This is done by the command `import numpy`. By convention, we rename `numpy` as `np` for convenience" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np # by convention, import numpy as np\n", "\n", "x = np.array( [ [1, 2, 3], [4, 5, 6] ] )\n", "\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Number of dimensions:\", x.ndim" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Dimensions:\", x.shape" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Size:\", x.size" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Length:\", len(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.array([1, 2, 3])\n", "\n", "print \"a=\", a\n", "\n", "print \"a*a=\", a * a #elementwise" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "b = np.array(np.ones((3,3)))*2\n", "print \"b=\", b\n", "c = np.array(np.ones((3,3)))\n", "print \"c=\", c" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "multiply elementwise" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"b*c = \", b*c" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now multiply as matrices" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"b*c = \", np.matrix(b)*np.matrix(c)\n", "print \"b*c = \", np.dot(b,c)\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, array can be created as a matrix" ] }, { "cell_type": "code", "collapsed": false, "input": [ "d = np.matrix([[1,1j,0],[1,2,3]])\n", "e = np.matrix([[1],[1j],[0]])\n", "\n", "print d*e" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Slicing for numpy arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy uses pass-by-reference semantics so it creates views into the existing array, without implicit copying. This is particularly helpful with very large arrays because copying can be slow." ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = np.array([1,2,3,4,5,6])\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We slice an array from a to b-1 with `[a:b]`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "y = x[0:4]\n", "print y" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since slicing does not copy the array, changing `y` changes `x`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "y[0] = 7\n", "print x\n", "print y" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To actually copy x, we should use .copy()" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = np.array([1,2,3,4,5,6])\n", "y = x.copy()\n", "y[0] = 7\n", "print x\n", "print y" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Commonly used Numpy functions: r\\_ and c\\_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We use `r_` to create integer sequences\n", "\n", "`r_[0:N]` creates an array listing every integer from 0 to N-1\n", "\n", "`r_[0:N:m]` creates an array listing every `m` th integer from 0 to N-1 " ] }, { "cell_type": "code", "collapsed": false, "input": [ "from numpy import r_ # import r_ function from numpy directly, so that we can call r_ directly instead of np.r_\n", "\n", "print r_[-5:5] # every integer from -5 ... 4\n", "\n", "print r_[0:5:2] # every other integer from 0 ... 4\n", "\n", "print abs( r_[-5:5] )\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "r\\_ stands for row concatenation, and the function r\\_[-5:5] is saying to row concatenate every element generated in the range [-5:5]. This is just one use case for row concatenation, but as you can imagine there are many others. The same goes for its cousin the c\\_ function, which performs a column concatenation." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from numpy import r_\n", "from numpy import c_\n", "\n", "row1 = [[1,0,0]]\n", "row2 = [[0,1,0]]\n", "row3 = [[0,0,1]]\n", "\n", "# we want to stack these three rows to create a 3x3 identity matrix\n", "# this is where the r_ function comes in handy\n", "\n", "print np.r_[row1,row2,row3] # 3x3 identity matrix appending vectors as rows" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What would have happened above if you had used `c_` instead of `r_` on `row1`, `row2`, and `row3`? You should try it in the box below" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print np.c_[# fill in # ] # vector created by appending elements as new columns" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some more examples:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "X = np.eye(3) # 3x3 Identity Matrix\n", "Y = np.ones([3,3]) # 3x3 Matrix of ones\n", "print \"X = \"\n", "print X\n", "print \"Y = \"\n", "print Y\n", "\n", "Z = r_[X,Y] # concatenate y to x as rows\n", "print \"\\n Row Concatenated [X ; Y] : \"\n", "print Z\n", "\n", "W = c_[X,Y] # concatenate y to x as columns\n", "print \"\\n Column Concatenated [X Y] : \\n \"\n", "print W" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plotting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this class, we will use `matplotlib.pyplot` to plot signals and images. \n", "\n", "To begin with, we import `matplotlib.pyplot` as `plt`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np\n", "import matplotlib.pyplot as plt # by convention, we import pyplot as plt\n", "from numpy import r_ # import r_ function from numpy\n", "\n", "\n", "x = r_[:1:0.01] # if you don't specify a number before the colon, the starting index defaults to 0\n", "a = np.exp( -x )\n", "b = np.sin( x*10.0 )/4.0 + 0.5\n", "\n", "# plot in browser instead of opening new windows\n", "%matplotlib inline" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`plt.plot(x, a)` plots `a` against `x`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once you started a figure, you can keep plotting to the same figure" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.plot( x, b )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To plot different plots, you can create a second figure" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.figure()\n", "plt.plot( x, b )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To label the axes, use `plt.xlabel()` and `plt.ylabel()`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.plot( x, b )\n", "\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also add title and legends using `plt.title()` and `plt.legend()`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.plot( x, b )\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )\n", "\n", "plt.title( \"Most important graph in the world\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many options you can specify in `plot()`, such as color and linewidth. You can also change the axis using `plt.axis`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a ,':r',linewidth=20)\n", "plt.plot( x, b ,'--k')\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )\n", "\n", "plt.title( \"Most important graph in the world\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )\n", "\n", "\n", "plt.axis( [0, 4, -2, 3] )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many other plotting functions. For example, we will use `plt.imshow()` for showing images and `plt.stem()` for plotting discretized signal" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# image\n", "plt.figure()\n", "\n", "data = np.outer( a, b ) # plotting the outer product of a and b\n", "\n", "plt.imshow(data)\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# stem plot\n", "plt.figure()\n", "plt.stem(a[::5]) # subsample by 5" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# xkcd style\n", "plt.xkcd()\n", "plt.plot( x, a )\n", "plt.plot( x, b )\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )\n", "\n", "plt.title( \"Most important graph in the world\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### To turn off xkcd style plotting, restart the kernel or run the command `plt.rcdefaults()`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logic" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "For loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indent matters in python. Everything indented belongs to the loop" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in [4, 6, \"asdf\", \"jkl\"]:\n", " print i\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in r_[0:10]:\n", " print i" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "If Else statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Same goes to If Else" ] }, { "cell_type": "code", "collapsed": false, "input": [ "if 1 != 0:\n", " print \"1 != 0\"\n", "else:\n", " print \"1 = 0\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Random Library" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The numpy random library should be your resource for all Monte Carlo simulations which require generating instances of random variables.\n", "\n", "The documentation for the library can be found here: http://docs.scipy.org/doc/numpy/reference/routines.random.html" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function $\\operatorname{rand}()$ can be used to generates a uniform random number in the range $[0,1)$" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from numpy import random\n", "\n", "print random.rand() # random number\n", "print random.rand(5) # random vector\n", "print random.rand(3,3) # random matrix" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see how we can use this to generate a fair coin toss (i.e. a discrete $\\mathcal{B}\\left(\\frac{1}{2}\\right)$ random variable)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = round(random.rand()) # Bernoulli(1/2) random variable\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's generate several fair coin tosses and plot a histogram of the results" ] }, { "cell_type": "code", "collapsed": false, "input": [ "k = 100\n", "x = [round(random.rand()) for _ in xrange(k)]\n", "# we could also use numpy's round function to element-wise round the vector\n", "x = np.round(random.rand(k))\n", "\n", "plt.hist(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can do something similar for several other distributions, and allow the histogram to give us a sense of what the distribution looks like. As we increase the number of samples we take from the distribution $k$, the more and more our histogram looks like the actual distribution." ] }, { "cell_type": "code", "collapsed": false, "input": [ "k = 1000\n", "\n", "discrete_uniform = random.randint(0,10,size=k) # k discrete uniform random variables between 0 and 9\n", "plt.figure(figsize=(6,3))\n", "plt.hist(discrete_uniform)\n", "plt.title('discrete uniform')\n", "\n", "continuous_uniform = random.rand(k)\n", "plt.figure(figsize=(6,3))\n", "plt.hist(continuous_uniform)\n", "plt.title('continous uniform')\n", "\n", "std_normal = random.randn(k) # randn generates elements from the standard normal\n", "plt.figure(figsize=(6,3))\n", "plt.hist(std_normal)\n", "plt.title('standard normal')\n", "\n", "# To generate a normal distribution with mean mu and standard deviation sigma, we must mean shift and scale the variable\n", "mu = 100\n", "sigma = 40\n", "normal_mu_sigma = mu + random.randn(k)*sigma\n", "plt.figure(figsize=(6,3))\n", "plt.hist(normal_mu_sigma)\n", "plt.title('N(' + str(mu) + ',' + str(sigma) + ')')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "^ We could do this all day with all sorts of distributions. I think you get the point." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Specifying a Discrete Probability Distribution for Monte Carlo Sampling" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following function takes $n$ sample from a discrete probability distribution specified by the two arrays `distribution` and `values`.\n", "\n", "As an example, let us suppose a random variable $X$ follows the following distribution:\n", "\n", "$$\n", "X = \\begin{cases} 1 \\ \\text{w.probability 0.1} \\\\ 2 \\ \\text{w.probability 0.4} \\\\ 3 \\ \\text{w.probability 0.2} \\\\ 4 \\ \\text{w.probability 0.2} \\\\ 5 \\ \\text{w.probability 0.05} \\\\ 6 \\ \\text{w.probability 0.05} \\end{cases}\n", "$$\n", "\n", "Then we would have:\n", "`distribution` = $\\begin{bmatrix} 0.1 , 0.4 , 0.2 , 0.2 , 0.05 , 0.05 \\end{bmatrix}$ and\n", "`values` = $\\begin{bmatrix} 1, 2, 3, 4, 5, 6 \\end{bmatrix}$" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def nSample(distribution, values, n):\n", " if sum(distribution) != 1:\n", " distribution = [distribution[i] / sum(distribution) for i in range(len(distribution))]\n", " rand = [random.rand() for i in range(n)]\n", " rand.sort()\n", " samples = []\n", " samplePos, distPos, cdf = 0, 0, distribution[0]\n", " while samplePos < n:\n", " if rand[samplePos] < cdf:\n", " samplePos += 1\n", " samples.append(values[distPos])\n", " else:\n", " distPos += 1\n", " cdf += distribution[distPos]\n", " return samples" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# collect k samples from X and plot the histogram\n", "samplesFromX = nSample([0.1, 0.4, 0.2, 0.2, 0.05, 0.05], [1, 2, 3, 4, 5, 6], k)\n", "plt.hist(samplesFromX)\n", "plt.ylim((0,1000))\n", "print \"Wow, if we normalized the y-axis that would be a PMF. Incredible! I should try that.\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Printing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are some fancy ways of printing:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"There are currently %d students enrolled in EE126.\\n\" % 109" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"At least %d of you will probably end up dropping. That is %f percent\" % ( 25, 25.0/109.0 * 100 )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## $\\mathcal{Q}$uestion 1: Monty Hall Proof and Simulation\n", "\n", "Provide a rigorous proof of the probability of winning the prize given a strategy of switching doors vs. a strategy of staying put. Simulate the Monty Hall problem for the case when you do switch doors and when you don't. Run the simulation 100,000 times for each case and determine the simulated probability of winning given each strategy. You may use the function below as a guide (or not). Make sure your simulation results match the analytical result you expect. If you need a refresher on the Monty Hall problem, the following video may be of some help:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.display import YouTubeVideo\n", "YouTubeVideo('Zr_xWfThjJ0')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Provide a proof that switching is a better strategy on the Monty Hall game show in this cell\n", "You can write in latex (cell type = markdown) or you can attach inline an image of the work if you choose. Make sure the proof ends up inline **in this cell**. We highly encourage you use latex. For inline latex (e.g. $x=5$) use single `$` around your math to render. For block equations use `$$`.\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Code to simulate Monty Hall goes here\n", "from __future__ import division\n", "\n", "def MontyHall(switch, n):\n", " # switch is a boolean which tells you whether or not to switch from the original door chosen\n", " # n is the number of times you want to simulate the action\n", " \n", " # Your beautiful code here... #\n", " \n", "print \"Probability of Winning if You Switch Doors: \", MontyHall(True,100000)\n", "print \"Probability of Winning if You Don't Switch: \" , MontyHall(False,100000)" ], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }