{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Problems from Hughes and Hase" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import scipy as sp\n", "from scipy import stats\n", "\n", "import matplotlib as mpl # As of July 2017 Bucknell computers use v. 2.x \n", "import matplotlib.pyplot as plt\n", "\n", "# Following is an Ipython magic command that puts figures in the notebook.\n", "# For figures in separate windows, comment out following line and uncomment\n", "# the next line\n", "# Must come before defaults are changed.\n", "%matplotlib notebook\n", "#%matplotlib\n", "\n", "# As of Aug. 2017 reverting to 1.x defaults.\n", "# In 2.x text.ustex requires dvipng, texlive-latex-extra, and texlive-fonts-recommended, \n", "# which don't seem to be universal\n", "# See https://stackoverflow.com/questions/38906356/error-running-matplotlib-in-latex-type1cm?\n", "mpl.style.use('classic')\n", " \n", "# M.L. modifications of matplotlib defaults using syntax of v.2.0 \n", "# More info at http://matplotlib.org/2.0.0/users/deflt_style_changes.html\n", "# Changes can also be put in matplotlibrc file, or effected using mpl.rcParams[]\n", "plt.rc('figure', figsize = (6, 4.5)) # Reduces overall size of figures\n", "plt.rc('axes', labelsize=16, titlesize=14)\n", "plt.rc('figure', autolayout = True) # Adjusts supblot parameters for new size" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 2.2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Twelve data points given:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "data = sp.array([5.33,4.95,4.93,5.08,4.95,4.96,5.02,4.99,5.24,5.25,5.23,5.01])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### a) Calculating the mean: $\\quad\\mu = \\frac{1}{N}\\sum_i x_i$" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mean = 5.07833333333\n" ] } ], "source": [ "print(\"mean =\",sum(data)/len(data))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mean = 5.07833333333\n" ] } ], "source": [ "print(\"mean =\",sp.mean(data))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### b) standard deviation: $\\quad\\sigma = \\sqrt{\\frac{1}{N-1} \\sum_i (x_i - \\mu)^2}$" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "standard deviation = 0.143579774046\n" ] } ], "source": [ "print(\"standard deviation =\",sp.sqrt(sum((data-sp.mean(data))**2)/(len(data)-1)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "standard deviation = 0.137467167797\n" ] } ], "source": [ "print(\"standard deviation =\",sp.std(data))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These results do not agree!! \n", "\n", "By default the scipy std method calculates $\\sigma_N$, which is similar to the\n", "$\\sigma_{N-1}$ given in Eq.(2.3) of H&H, except the denominator is $N$ instead of $N-1$. The difference doesn't usually matter, and we won't go into this in any depth now. But if we set the 'ddof=1' option scipy will calculate $\\sigma_{N-1}$.\n", "\n", "Remember: you can see all the details of sp.std by typing sp.std?." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "standard deviation = 0.143579774046\n" ] } ], "source": [ "print(\"standard deviation =\",sp.std(data,ddof=1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### c) Standard error, or standard deviation of the mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use Eq.(2.7): $\\quad\\alpha = \\frac{\\sigma_{N-1}}{\\sqrt{N}}$." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "standard error = 0.0414479105979\n" ] } ], "source": [ "print(\"standard error =\",sp.std(data,ddof=1)/sp.sqrt(len(data)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### d) Formatted result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$\\mbox{sensitivity} = 5.071 \\pm 0.041 $" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sample $n$ random numbers from the normal distribution with mean $\\mu$, standard deviation $\\sigma$, and \n", "pdf\n", "\\begin{equation}\n", "p(x) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp\\left(-(x-\\mu)^2/\\sigma^2\\right)\n", "\\end{equation}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 2.3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The standard error, or standard deviation of the mean, is given by Eq.(2.7):\n", "\n", "$$ \\alpha = \\frac{\\sigma_{N-1}}{\\sqrt{N}}. $$\n", "\n", "To decrease $\\alpha$ by a factor of 10, the denominator must be increased by the \n", "same factor, which means that $N$ must increase by a factor of 100. Translating to the described experiment, this means that data should be collected for 100 minutes (assuming that everything in the experiment is stable for that length of time).\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ### Problem 2.6" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(i) If the mean is $\\bar{\\delta} = 3.27346$, and the standard error (standard deviation of the mean) is $\\alpha = 0.01913$, I would report $\\delta = 3.27 \\pm 0.02$ (although some might report this as $\\delta = 3.273 \\pm 0.019)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3.2" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import sympy as sym # import sympy for symbolic integration\n", "sym.init_printing() # for LaTeX formatted output\n", "\n", "a, x, mu = sym.symbols('a x mu') # must declare symbolic variables in sympy\n", " # I will use mu for x-bar" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the probability distribution function.
\n", "(The conditional will be incorporated in the limits of integration.)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "p = 1/a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "a) A probability distribution is normalized if the integral over all space is one, i.e., $\\int_{-\\infty}^\\infty P_U(x;\\bar{x},a) \\, dx = \\int_{\\mu-a/2}^{\\mu+a/2}P_U(x;\\bar{x},a) \\, dx = 1$." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAPoAAAAqBAMAAABo/FshAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2ZiKJ\nRLuWvIZ2AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAECklEQVRYCc1XTUhUURQ+T+fXGW1IyEULhykQ\n2zgQFJHYbIKgRa6iaOH0Q0FCGUFUG4da6MqkRQQJDQQt2iTUQmihtAgDISloG0SrFqGZYGnYfe/e\nc+85995xRplFb+H7vnPO933e9zfvAfwv2+lcE/6T+PkdmQS3R5uQ3jW2vKN0gKdNSId0E9JfNLCA\nYMQ3RNO3cnHUZu3pPDGemX/kPygfyZCGJD1yaVht0j+TuPZh6NPeDKR9iyfpoUvjap0eXCIpe6ow\nQSiFByhR2KRHLo2rdXqSLupBDo54UsLSLDlEOGLSI5fG1Tr91DR6if01CH4RSiH7L1XDpEcujat1\neg+JCDYgvkQ4hTHP3WXSQ5dtqDE9s04iglXoyJ8jBQp7KZFYp0cu21BjeqpITXvh2cgcLRD8nGAF\ndbp0aVg9dr2nGlkkJqlp19TJO4u0QPCs00jd+nlXDkiX7alD5WxJ6uv/TczVnqnv4le/rG1pdZJ5\nq0BofRe/+j7x4DDOzglAekn17YYouy5nuZlRs/oAY5TYIXG8O+yGELkudrpW0whYY4wSOyS2qrp2\nQ5RdFztdq2kE/GaMEgyJlSH6iQn+qC42yLDrgumOmqhAW9KixBiSLUJrJSxhBDbkWPjX44Lpjtqo\nADK4IFqUGENaKtA9GJY21Aw2FBU7jwumE/Xug+G2H3ZthluolqfDrWcLhX0XCoURMSKih3LhbHRy\nScN2MfxtoXCoUAif/ZY6rJAtVn/tIvpepMBLy127xwXX7qhJuO+YYRtDxL3cH4ii+AmTGzZwcMsj\n76iNSljipUSLPGQAMqtZUdIn1033uODaHTULwgWxYkRUSLACqfXjoqLvWDddX5DGRaW7ajMi0BXG\nKFEh8bX3k1OTotH+V3U96a6LSnfVNAK+MgYzE9+woEL0z0Mbvtx40qVLZvxHCdUq3VXjQLR/x5h4\n7f+wqCrBdAT0C0C2zBuKRTvp0gVZPD6wV7ZdNZWpWxlLyRwkykjkXv90t47wBmXygXAD4DKtClxH\n3V2l84kiJK2X2k/Y55NYlXvZuwgwWuKNOuoOtqKWZSdduw3JM6E5BdKlL+ek6yGm1l9cbWU9IEEr\nXlxWXT3wWNV1OZZjA4bIx6Xk5otLvAbz7csc55pd1QiB69Je8/FB1eSL6yF6qf1hiyNNlxHpvetS\n88pkavLFlShptxCkKowakqgarJDrMu7MqAJTky+utjxTPGaMEPsYiZbjkq4QAYNUzb642BdSvAJv\nmAxJZhiR3rsuZyDjvzGYmn1xdZa0H8AJgCeEGtg5aLBCjkusAml/OlfTL67MUeOb6V8YKxpK0HeC\nEdourxbmb2KP77mafXG9NpMt4oXLmx4smiGNbJe+zc0V3aQgUv8DTdEowOkC4s8AAAAASUVORK5C\nYII=\n", "text/latex": [ "$$- \\frac{1}{a} \\left(- \\frac{a}{2} + \\mu\\right) + \\frac{1}{a} \\left(\\frac{a}{2} + \\mu\\right)$$" ], "text/plain": [ " a a \n", " - ─ + μ ─ + μ\n", " 2 2 \n", "- ─────── + ─────\n", " a a " ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sym.integrate(p,(x,mu-a/2,mu+a/2))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAPBAMAAAArJJMAAAAAHlBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAACGjDitAAAACXRSTlMAVO8Qq5l2zWYZcMvdAAAACXBIWXMAAA7EAAAOxAGV\nKw4bAAAAHUlEQVQIHWNgAANGZQYGk5DJQDYbqQSr03QPsBkAJYgIYEZbtZEAAAAASUVORK5CYII=\n", "text/latex": [ "$$1$$" ], "text/plain": [ "1" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sym.simplify(_) # The underscore \"_\" is like the Mathematica %\n", " # it refers to the previous output. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "b) The mean is just the first moment of the distribution given by Eq.(3.4):\n", "\n", "$$ \\bar{x} = \\int_{-\\infty}^\\infty P(x) x\\, dx $$" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAOEAAAA1BAMAAABFMpFwAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMkS7mXYiie9U\nZqsqREkJAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAESklEQVRYCe2YTWgTQRTH33Y3zWdr1IOIYGsU\n7EFsxW9FDIqCKDSgJ0GNFz0JUcGKIOamqJSIoscEPVQFofiFomAu2gqFVjwIChIriAfBiopUCvHN\n7M7OzO5sshl6dA47//fm/ebtzO7OTAKgU4aOpnWwxKnjOhgyiVJntw56ByZ1MGTMkjWtg26E/pIO\nhxlz8d865Foo53Q4wqR+6JHjWs+f5DKLehk3eLAdHltlFqlzSNVkNZiyGAUSBZmz8rKttA4Sb4eH\ntCN3KgHbGamR+p1tuNe2MJOcmMD4/bDPpbhYwqVf3UNXpBLJSi2nBcs4PSk3um2rAKwVY4dd2xXR\nIsoFg8tchyRMHM62sVfSoOLi+zc/2y81cvo8QLJen+IOpsoIGGsssRfWhHWsAPCiXhc8uJKgzy0D\nsN3VsijLJrfI2xQtWH3cI6r4lGjZOlkVfM9hkFmpIlO0NickkxvPUSarsZrj8WCwhUcyJU6jMQ3H\n5qrRaJ4Bck2ns6vU/iZt+70ZT8nhxPoguh5av9lYPGhsWIzjuoP4k9n+A47Lg8ElHsrUCSZIffDy\neW9GaxjIlEUCXo1oN2KRr6NnsSLFzbgb6BM6lLb9wvWIoEXJ0EQfmAX8NH6JjVy357kmimFwC2A9\n2v1Z4pXKSsniBkPbCtBVBQjaNtpqHCGKYbAcjBm0FdsGuZF5q0lZBnPqWKbQkchklt7PZGooMR1Z\n+uMEVxQyfiAY+eYEDNPRnaZc9UHNxojpyKNudYyYjj5ixRjljPwow6bnJMAmA59jwPZvz6ofi+Lj\nr+DcKLb/L+KohaMMy7gOJzQR/K525pFXYGYeytUKgOJdlT4Y4SjjZDR+QnR6D+5Uw9izotDv1I9B\nVx+cu1b1fO42L92EcJRxMqb+3C5eLOLSmbfDvVf6nfoxGD9zIXYbgxVrTjIndeIeZZyM7MDYVpTC\nuPGISi/mHhh7eCRT0QpTtDaLjmmUqEg6dhe+Bcpyhnq9GDyxgw3FUoWrmFjI5iOWcta2PopOUeNq\nhsWLxZ0lqqNGm+XLN9H0HWX2Oq1rxCiAUdfsrKL0YZE+O8DM2rV0nSda6qMMdlkRo8SMRje2BGHw\nXsZsK1XgXvVRBtuv8xiq+BhhJOgEhIHxvIezzZfcqz7KYPtxHkOVkDGVCzgBYWA06H3zdBfCFDKG\niJ6NkNYzSvsT3WxCXsjt3sxkNmcydAsISamOnS0OvPUxtpjAF/4/o29KZsExu7MaHziSbXZTARnD\noIquF0Oi6T8MCxUcusKgCvITwDOFO4xLE30A8D0bpn9/jCbam9bOqI9uTcONoUtaC78eGvkLkafQ\n65+15h5N1KzBognVwa95Rk10AOBcGrz/NDVPhxF6KPmD4jEYAb8YGybWREcgfuUvpKYa9q1u1EOt\nAsSuzEB792t1rw28mujVu0OfoQfe1ioN+lY3aaK99fpPWHxx19ecutsG3mD0H194ZngFT5WZAAAA\nAElFTkSuQmCC\n", "text/latex": [ "$$- \\frac{\\left(- \\frac{a}{2} + \\mu\\right)^{2}}{2 a} + \\frac{\\left(\\frac{a}{2} + \\mu\\right)^{2}}{2 a}$$" ], "text/plain": [ " 2 2\n", " ⎛ a ⎞ ⎛a ⎞ \n", " ⎜- ─ + μ⎟ ⎜─ + μ⎟ \n", " ⎝ 2 ⎠ ⎝2 ⎠ \n", "- ────────── + ────────\n", " 2⋅a 2⋅a " ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sym.integrate(p*x,(x,mu-a/2,mu+a/2))" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAAwAAAANBAMAAABvB5JxAAAALVBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAOrOgAAAADnRSTlMAMu92q4ndmc0QVLsiRAus\n9U8AAAAJcEhZcwAADsQAAA7EAZUrDhsAAABUSURBVAgdY2BgVGBgdmBgYE1gYCtgYOAoYJi3gAGE\n101gAOEKBgaGMgaGVE4GhmwGnlesDJzPGNjfSDFwPQ82MDVgYGkAyjMwMBmAqXMCYOoamAQAAh4P\nsS7zeAEAAAAASUVORK5CYII=\n", "text/latex": [ "$$\\mu$$" ], "text/plain": [ "μ" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sym.simplify(_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "c) The square of the standard deviation, or variance, is given by Eq.(3.5):\n", "\n", "$$ \\sigma^2 = \\int_{-\\infty}^\\infty P(x)(x-\\bar{x})^2\\, dx $$" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAEIAAAAwBAMAAABXkLERAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAInarRM2ZVBDdiWbv\nuzJCz3LGAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABvklEQVQ4Ed2Uvy8DYRjHv9Vq7656PYvBwlwS\nIiaD3CwiFwsJoYO0U+MsjC7EIJG0MYhNY+jQRGLFUonBQGISG/4DhChCPW/fH4dca+YZ3uf7fJ7v\n+7zvDfcCgdFVU6H6nMlyUIov+RsLOV86Qn5nUZfj0qWnrJJxsM6TYYX9YYKJHVmedcu8FwTIIlTe\nE7OhFYTDDj1KB7EOxN5EaexLHqtKRazPxYso/SP1bukgNmprT6LskRglpeqMnRKxiYlrAPE0c/hs\nvQj0OkBLN+GOUq+HEYyRVKxzy0NohS6vE40cYxbmxNIVfAYYJ4D2DhySY2MfObTVanekJSN55gHz\nFrZJznvYpMRDsHbg2gW60vEi8XNoH6KvWM2rO8JV3aPBr4ixA3hwRruwYwHm6yJh7RkJZ0E6OMMR\nYg8MTU+ydRwH/UUm6sFZJJOzWbmcZutq6nbAZqIenMmqlY76GUHsp+ef1Or/bCT+8HeWUzfNb79m\nR53mjkskLpo6Iv570cCXqDRoKJyc2Z1TRaDIT6HNDexImK8ieiqLwJwsIK6erkCH7iAuX7NAA8KV\n32aYdI9K8GZJh7DR/FtgZIalWeRPRZKSXfCaO44AAAAASUVORK5CYII=\n", "text/latex": [ "$$\\frac{\\sqrt{3} \\sqrt{a^{2}}}{6}$$" ], "text/plain": [ " ____\n", " ╱ 2 \n", "√3⋅╲╱ a \n", "──────────\n", " 6 " ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sym.sqrt(sym.integrate(p*(x-0)**2,(x,-a/2,a/2)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Normally distributed pasta bags with a mean weight of 502 g, and an s.d. of 14 g." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": true }, "outputs": [], "source": [ "mean = 502.\n", "sigma = 14." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "What is the probability that a bag contains less than 500 g?
\n", "This information is given directly by the cumulative distribution function (c.d.f.)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAIwAAAAPBAMAAADEyjp7AAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEJmJZjLNVN0i77ur\nRHZ72Yd1AAAACXBIWXMAAA7EAAAOxAGVKw4bAAACV0lEQVQ4EaWTwUsUYRjGf7OuzY7rrlNeJCTX\njbrUYVGLyKgFO0nY4j/QQocOQQ7RMVipQ4SBg0bUyTwEpUh66mDRFkYRZkuHDl30DwjLDE0rt/f7\n3hnq3gf7zLfv9zy/+eadb2BPzxF0DJqLyHj3E/Dy8yWc/X2laPGSPxio1+vuDbTorHbVogwXaAu1\nOmIuI3g5KkXaafjNrsC5Ce6k1B/X11HvGO53LSbgtWZI3qehbOZkp1Wym7QM8wKm6IejtB9ek4Xz\nS2Hk/RLwQ4tX4E4UTFdxjQ1uX1TJzNBR5iG8Lz2Fik/WrFflp95PNWdDbirFXmjTDC1VMpsyh4LB\nWDEPNeQL5hcsB38xsdc8lMEsz9ETZTpyZHYMJRkKxgrOdVNgdPc3sa4oZmHgALG3raCY5npfMcpM\nFGiU5sE+BGPFO9ZpCpl1TxbOFRQzx0Qt8o5f8xXDqQ2Z2cxELsIUDMYKHK8JJlX1ZDcxRjozHHsb\nZhTjvhuVmc3EG3VLgrEihKZJkTzOPw8Fia3Yy5T2/QzZbV8z0jbXtLgVwVjxQtJSyeZAWlzRFjeX\n5Ryp9x481+Ij2WxgM6RnSZoXenVxcXvJSsuaxVzGC+fhrN64qUxiTb11P8I4X6G5aDPmSCXKgpEx\nrdI0S2qLxhzZUI7fQW2DHNhUWb1iGw1t32U36TAK3mBvyZwn+KmSLFJZ4W531xtSgfNAMfKF9IcY\nL6dxd7T40WcgDrauvoJb8q+3vqDyIf8Mhur1HzgnP5dIvN2QhbETndJA483kD9W02PjSfpo2aHD/\nPf4ABYHdd9UPJxEAAAAASUVORK5CYII=\n", "text/latex": [ "$$0.443201503184$$" ], "text/plain": [ "0.443201503184" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sp.stats.norm.cdf(500,mean,sigma)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In a sample of 1000 bags, how many are expected to contain at least 530 g?
\n", "This information is given indirectly by the c.d.f. The probability of one bag containing \n", "more than 530 is (1 - c.d.f), and we must multiply by the number of bags." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAH8AAAAPBAMAAAA/sQ3hAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACVElEQVQoFaWTS2gTURSGv2k7eU6bIIhUNzFg\nuxBxoCgiiNkJbjq46MJNY8DiA22oYvBBDW5d1IJKVfCxcuGi3ehKbBQqCAWDCOLGxI1FFK3S1mqp\n43/vROneS/jn5pzzfzn3zglOvq+AFWB/qVIpp2c6tuH2zhUUMGtDZU+04UDlkNl15HBnR6ot1wDx\nZawo9TUMw2IyDMuk6+496LwGTo5GE94GuLfpzqoq5dMGJ1quw3ADK0pthhjpM0/hI5xnoGcRvFUy\nd93ScEDsCrGcql74vINNLddNGC5YUaoMp4XQ2gmNAE+AxASDU/AyIDNFfF4tffI5BQeJXNOBAFaM\nj0QtAizBWN0CFDRHEGDQx1uAeNpnbAej/HNNBiqyAu06xJdnBfe7ALUWwL2vvABJdbAM7wWIhXOC\ntlyJH9pZ0XNUjMBZdhTrL0cA59wWJQRQ/+nfuDUBuLhifjVypYraWgFXZ9Ta7aiDvwA4W7UAHvNm\nlTgCdB6ZnFBd5MobixVd+ZT5wvb1a49AUm9THdA1u2+B1wbwAe+nAtbl5eSwoqdeMcfVYFWX2Igu\n0cnSvhoBdD+LrmbEZ1wNKm2svEIlVvRlsAi31EHQp6kK7B1kFtcA0sXOoaHh6zPzYjUjl+bSy1ox\ntP4c6PPADNJWNaY5SPqkvtkOusbpz6pIEXXQ3nJtrIwcw4oZl4bc61Blqu5ejQBdTRo1C/Aeuk/k\nJ+NzOeBz5GI6DH9FYq60u65J6y1p7i88L9B2dOUkXMrvgp47j5qM5Kvyx/cuNTtK+jNZqwL/t/4A\ndaDF89K/2h4AAAAASUVORK5CYII=\n", "text/latex": [ "$$22.7501319482$$" ], "text/plain": [ "22.7501319482" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1000*(1-sp.stats.norm.cdf(530,mean,sigma))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3.7\n", "\n", "Radioactive decays recorded during 58 successive one-second experiments." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "data = sp.array([[1,1],[2,0],[3,2],[4,3],[5,6],[6,9],[7,11],[8,8],[9,8],\\\n", " [10,6],[11,2],[12,1],[13,1]])\n" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "For fun, let's reproduce Fig.3.8 from Hughes & Hase." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "/* Put everything inside the global mpl namespace */\n", "window.mpl = {};\n", "\n", "\n", "mpl.get_websocket_type = function() {\n", " if (typeof(WebSocket) !== 'undefined') {\n", " return WebSocket;\n", " } else if (typeof(MozWebSocket) !== 'undefined') {\n", " return MozWebSocket;\n", " } else {\n", " alert('Your browser does not have WebSocket support.' +\n", " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n", " 'Firefox 4 and 5 are also supported but you ' +\n", " 'have to enable WebSockets in about:config.');\n", " };\n", "}\n", "\n", "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n", " this.id = figure_id;\n", "\n", " this.ws = websocket;\n", "\n", " this.supports_binary = (this.ws.binaryType != undefined);\n", "\n", " if (!this.supports_binary) {\n", " var warnings = document.getElementById(\"mpl-warnings\");\n", " if (warnings) {\n", " warnings.style.display = 'block';\n", " warnings.textContent = (\n", " \"This browser does not support binary websocket messages. \" +\n", " \"Performance may be slow.\");\n", " }\n", " }\n", "\n", " this.imageObj = new Image();\n", "\n", " this.context = undefined;\n", " this.message = undefined;\n", " this.canvas = undefined;\n", " this.rubberband_canvas = undefined;\n", " this.rubberband_context = undefined;\n", " this.format_dropdown = undefined;\n", "\n", " this.image_mode = 'full';\n", "\n", " this.root = $('
');\n", " this._root_extra_style(this.root)\n", " this.root.attr('style', 'display: inline-block');\n", "\n", " $(parent_element).append(this.root);\n", "\n", " this._init_header(this);\n", " this._init_canvas(this);\n", " this._init_toolbar(this);\n", "\n", " var fig = this;\n", "\n", " this.waiting = false;\n", "\n", " this.ws.onopen = function () {\n", " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n", " fig.send_message(\"send_image_mode\", {});\n", " if (mpl.ratio != 1) {\n", " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n", " }\n", " fig.send_message(\"refresh\", {});\n", " }\n", "\n", " this.imageObj.onload = function() {\n", " if (fig.image_mode == 'full') {\n", " // Full images could contain transparency (where diff images\n", " // almost always do), so we need to clear the canvas so that\n", " // there is no ghosting.\n", " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n", " }\n", " fig.context.drawImage(fig.imageObj, 0, 0);\n", " };\n", "\n", " this.imageObj.onunload = function() {\n", " this.ws.close();\n", " }\n", "\n", " this.ws.onmessage = this._make_on_message_function(this);\n", "\n", " this.ondownload = ondownload;\n", "}\n", "\n", "mpl.figure.prototype._init_header = function() {\n", " var titlebar = $(\n", " '
');\n", " var titletext = $(\n", " '
');\n", " titlebar.append(titletext)\n", " this.root.append(titlebar);\n", " this.header = titletext[0];\n", "}\n", "\n", "\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "\n", "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n", "\n", "}\n", "\n", "mpl.figure.prototype._init_canvas = function() {\n", " var fig = this;\n", "\n", " var canvas_div = $('
');\n", "\n", " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n", "\n", " function canvas_keyboard_event(event) {\n", " return fig.key_event(event, event['data']);\n", " }\n", "\n", " canvas_div.keydown('key_press', canvas_keyboard_event);\n", " canvas_div.keyup('key_release', canvas_keyboard_event);\n", " this.canvas_div = canvas_div\n", " this._canvas_extra_style(canvas_div)\n", " this.root.append(canvas_div);\n", "\n", " var canvas = $('');\n", " canvas.addClass('mpl-canvas');\n", " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n", "\n", " this.canvas = canvas[0];\n", " this.context = canvas[0].getContext(\"2d\");\n", "\n", " var backingStore = this.context.backingStorePixelRatio ||\n", "\tthis.context.webkitBackingStorePixelRatio ||\n", "\tthis.context.mozBackingStorePixelRatio ||\n", "\tthis.context.msBackingStorePixelRatio ||\n", "\tthis.context.oBackingStorePixelRatio ||\n", "\tthis.context.backingStorePixelRatio || 1;\n", "\n", " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n", "\n", " var rubberband = $('');\n", " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n", "\n", " var pass_mouse_events = true;\n", "\n", " canvas_div.resizable({\n", " start: function(event, ui) {\n", " pass_mouse_events = false;\n", " },\n", " resize: function(event, ui) {\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " stop: function(event, ui) {\n", " pass_mouse_events = true;\n", " fig.request_resize(ui.size.width, ui.size.height);\n", " },\n", " });\n", "\n", " function mouse_event_fn(event) {\n", " if (pass_mouse_events)\n", " return fig.mouse_event(event, event['data']);\n", " }\n", "\n", " rubberband.mousedown('button_press', mouse_event_fn);\n", " rubberband.mouseup('button_release', mouse_event_fn);\n", " // Throttle sequential mouse events to 1 every 20ms.\n", " rubberband.mousemove('motion_notify', mouse_event_fn);\n", "\n", " rubberband.mouseenter('figure_enter', mouse_event_fn);\n", " rubberband.mouseleave('figure_leave', mouse_event_fn);\n", "\n", " canvas_div.on(\"wheel\", function (event) {\n", " event = event.originalEvent;\n", " event['data'] = 'scroll'\n", " if (event.deltaY < 0) {\n", " event.step = 1;\n", " } else {\n", " event.step = -1;\n", " }\n", " mouse_event_fn(event);\n", " });\n", "\n", " canvas_div.append(canvas);\n", " canvas_div.append(rubberband);\n", "\n", " this.rubberband = rubberband;\n", " this.rubberband_canvas = rubberband[0];\n", " this.rubberband_context = rubberband[0].getContext(\"2d\");\n", " this.rubberband_context.strokeStyle = \"#000000\";\n", "\n", " this._resize_canvas = function(width, height) {\n", " // Keep the size of the canvas, canvas container, and rubber band\n", " // canvas in synch.\n", " canvas_div.css('width', width)\n", " canvas_div.css('height', height)\n", "\n", " canvas.attr('width', width * mpl.ratio);\n", " canvas.attr('height', height * mpl.ratio);\n", " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n", "\n", " rubberband.attr('width', width);\n", " rubberband.attr('height', height);\n", " }\n", "\n", " // Set the figure to an initial 600x600px, this will subsequently be updated\n", " // upon first draw.\n", " this._resize_canvas(600, 600);\n", "\n", " // Disable right mouse context menu.\n", " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n", " return false;\n", " });\n", "\n", " function set_focus () {\n", " canvas.focus();\n", " canvas_div.focus();\n", " }\n", "\n", " window.setTimeout(set_focus, 100);\n", "}\n", "\n", "mpl.figure.prototype._init_toolbar = function() {\n", " var fig = this;\n", "\n", " var nav_element = $('
')\n", " nav_element.attr('style', 'width: 100%');\n", " this.root.append(nav_element);\n", "\n", " // Define a callback function for later on.\n", " function toolbar_event(event) {\n", " return fig.toolbar_button_onclick(event['data']);\n", " }\n", " function toolbar_mouse_event(event) {\n", " return fig.toolbar_button_onmouseover(event['data']);\n", " }\n", "\n", " for(var toolbar_ind in mpl.toolbar_items) {\n", " var name = mpl.toolbar_items[toolbar_ind][0];\n", " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n", " var image = mpl.toolbar_items[toolbar_ind][2];\n", " var method_name = mpl.toolbar_items[toolbar_ind][3];\n", "\n", " if (!name) {\n", " // put a spacer in here.\n", " continue;\n", " }\n", " var button = $('');\n", " button.click(method_name, toolbar_event);\n", " button.mouseover(tooltip, toolbar_mouse_event);\n", " nav_element.append(button);\n", " }\n", "\n", " // Add the status bar.\n", " var status_bar = $('');\n", " nav_element.append(status_bar);\n", " this.message = status_bar[0];\n", "\n", " // Add the close button to the window.\n", " var buttongrp = $('
');\n", " var button = $('');\n", " button.click(function (evt) { fig.handle_close(fig, {}); } );\n", " button.mouseover('Stop Interaction', toolbar_mouse_event);\n", " buttongrp.append(button);\n", " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n", " titlebar.prepend(buttongrp);\n", "}\n", "\n", "mpl.figure.prototype._root_extra_style = function(el){\n", " var fig = this\n", " el.on(\"remove\", function(){\n", "\tfig.close_ws(fig, {});\n", " });\n", "}\n", "\n", "mpl.figure.prototype._canvas_extra_style = function(el){\n", " // this is important to make the div 'focusable\n", " el.attr('tabindex', 0)\n", " // reach out to IPython and tell the keyboard manager to turn it's self\n", " // off when our div gets focus\n", "\n", " // location in version 3\n", " if (IPython.notebook.keyboard_manager) {\n", " IPython.notebook.keyboard_manager.register_events(el);\n", " }\n", " else {\n", " // location in version 2\n", " IPython.keyboard_manager.register_events(el);\n", " }\n", "\n", "}\n", "\n", "mpl.figure.prototype._key_event_extra = function(event, name) {\n", " var manager = IPython.notebook.keyboard_manager;\n", " if (!manager)\n", " manager = IPython.keyboard_manager;\n", "\n", " // Check for shift+enter\n", " if (event.shiftKey && event.which == 13) {\n", " this.canvas_div.blur();\n", " // select the cell after this one\n", " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n", " IPython.notebook.select(index + 1);\n", " }\n", "}\n", "\n", "mpl.figure.prototype.handle_save = function(fig, msg) {\n", " fig.ondownload(fig, null);\n", "}\n", "\n", "\n", "mpl.find_output_cell = function(html_output) {\n", " // Return the cell and output element which can be found *uniquely* in the notebook.\n", " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n", " // IPython event is triggered only after the cells have been serialised, which for\n", " // our purposes (turning an active figure into a static one), is too late.\n", " var cells = IPython.notebook.get_cells();\n", " var ncells = cells.length;\n", " for (var i=0; i= 3 moved mimebundle to data attribute of output\n", " data = data.data;\n", " }\n", " if (data['text/html'] == html_output) {\n", " return [cell, data, j];\n", " }\n", " }\n", " }\n", " }\n", "}\n", "\n", "// Register the function which deals with the matplotlib target/channel.\n", "// The kernel may be null if the page has been refreshed.\n", "if (IPython.notebook.kernel != null) {\n", " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n", "}\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "x1 = sp.linspace(0,upper,upper+1)\n", "y1 = sp.stats.poisson.pmf(x1,mean)\n", "x2 = sp.linspace(0,upper,500)\n", "y2 = sp.stats.norm.pdf(x2,mean,sp.sqrt(mean))\n", "plt.figure(2)\n", "plt.xlim(0,upper)\n", "plt.axhline(0)\n", "plt.scatter(x1,y1)\n", "plt.plot(x2,y2);" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### Version details\n", "\n", "`version_information` is from J.R. Johansson (jrjohansson at gmail.com)
\n", "See Introduction to scientific computing with Python:
\n", "http://nbviewer.jupyter.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-0-Scientific-Computing-with-Python.ipynb
\n", "for more information and instructions for package installation.
\n", "\n", "If `version_information` has been installed system wide (as it has been on linuxremotes), continue with next cell as written. If not, comment out top line in next cell and uncomment the second line." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading extensions from ~/.ipython/extensions is deprecated. We recommend managing extensions like any other Python packages, in site-packages.\n" ] } ], "source": [ "%load_ext version_information\n", "\n", "#%install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "application/json": { "Software versions": [ { "module": "Python", "version": "3.6.1 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]" }, { "module": "IPython", "version": "6.1.0" }, { "module": "OS", "version": "Linux 3.10.0 327.36.3.el7.x86_64 x86_64 with redhat 7.2 Maipo" }, { "module": "scipy", "version": "0.19.1" }, { "module": "matplotlib", "version": "2.0.2" }, { "module": "sympy", "version": "1.1" } ] }, "text/html": [ "
SoftwareVersion
Python3.6.1 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
IPython6.1.0
OSLinux 3.10.0 327.36.3.el7.x86_64 x86_64 with redhat 7.2 Maipo
scipy0.19.1
matplotlib2.0.2
sympy1.1
Tue Aug 01 11:08:17 2017 EDT
" ], "text/latex": [ "\\begin{tabular}{|l|l|}\\hline\n", "{\\bf Software} & {\\bf Version} \\\\ \\hline\\hline\n", "Python & 3.6.1 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] \\\\ \\hline\n", "IPython & 6.1.0 \\\\ \\hline\n", "OS & Linux 3.10.0 327.36.3.el7.x86\\_64 x86\\_64 with redhat 7.2 Maipo \\\\ \\hline\n", "scipy & 0.19.1 \\\\ \\hline\n", "matplotlib & 2.0.2 \\\\ \\hline\n", "sympy & 1.1 \\\\ \\hline\n", "\\hline \\multicolumn{2}{|l|}{Tue Aug 01 11:08:17 2017 EDT} \\\\ \\hline\n", "\\end{tabular}\n" ], "text/plain": [ "Software versions\n", "Python 3.6.1 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\n", "IPython 6.1.0\n", "OS Linux 3.10.0 327.36.3.el7.x86_64 x86_64 with redhat 7.2 Maipo\n", "scipy 0.19.1\n", "matplotlib 2.0.2\n", "sympy 1.1\n", "Tue Aug 01 11:08:17 2017 EDT" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "version_information scipy, matplotlib, sympy" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 1 }