{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Random Numbers\n", "\n", "The code we have seen and written so far is\n", "considered *deterministic*: it runs exactly the same\n", "each time and generates the same output.\n", "Another very common requirement of programs\n", "is to utilize random numbers. This is particularly\n", "common and helpful as random numbers\n", "are fundamental to *stochastic* simulations, which\n", "attempt to exploit randomness in order to mimic the\n", "behavior of some process. For instance, stochastic \n", "simulations are used to model the stock market,\n", "model physical, biological, and chemical processes.\n", "In addition, to processes that are truly random, stochastic\n", "simulations are often used for to approximate a solution\n", "to a problem that is simply infeasible to solve analytically.\n", "\n", "Unfortunately, creating truly random numbers is an extremely\n", "difficult task. (How would we generate them? -- we can't ask\n", "a computer to flip a coin unless we can say directly what happens\n", "when we flip a coin, which would then make it deterministic).\n", "Instead, we rely on *pseudorandom numbers*, that look like they\n", "are random, when they are actually not truly random. These numbers\n", "are created by *pseudorandom number generators*. There are a variety\n", "of algorithms used by *pseudorandom number generators*, but\n", "thankfully most programming languages, Python included, have\n", "predefined ways of creating these pseudorandom numbers.\n", "\n", "## Random Module\n", "\n", "In Python, the `random` module provides a large number of functions\n", "for generating \"random\" (actually pseudorandom) numbers in differing formats. The full list of functions can be seen in the\n", "[documentation for the `random` module](https://docs.python.org/3/library/random.html).\n", "We'll discuss a few of these now, but know that there are many\n", "more for doing more specific tasks involving randomness\n", "and for a variety of other distributions.\n", "\n", "### Examples\n", "\n", "Before getting started, like with the `math` module, we must\n", "first `import` the module. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Single random integer\n", "\n", "To generate a single random integer, we use the `randint(a,b)`\n", "function that generates a single random integer between \n", "`a` and `b` (inclusive, so integer $n$ such that $a \\leq n \\leq b$).\n", "\n", "Let's try simulating flipping a coin with this, where a 0 represents\n", "a heads and a 1 represents a tails." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "coin = random.randint(0,1)\n", "print(coin)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each time we run that code, it's like a new random flip of\n", "the coin. We can simulate multiple random flips by putting\n", "this code into a loop. Let's perform 10 flips:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(10):\n", " coin = random.randint(0,1)\n", " print(coin)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could combine this with our other \"building blocks\" to\n", "count up the number of \"heads\" (0s) in `n` flips." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = 10\n", "num_heads = 0\n", "for i in range(n):\n", " coin = random.randint(0,1)\n", " if coin == 0:\n", " num_heads += 1\n", "print(num_heads)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could have changed the arguments to the `randint` function\n", "to generate over a different range of integers (the choice\n", "depends on your application)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result = random.randint(1,1000)\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Real-valued Random Numbers\n", "\n", "The previous example was generating integers, but sometimes it's necessary\n", "to have numbers from real-valued distributions. There are a lot of distributions\n", "available. Two of the most commonly used ones are:\n", "* `uniform(a,b)` - returns a random floating point number $n$ such that $a \\leq n \\leq b$\n", "* `guass(mu, sigma)` - returns a random number draw from Gaussian distribution with mean `mu`\n", " and standard deviation `sigma`\n", "\n", "Let's look at a couple examples:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = random.uniform(-1,1)\n", "print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = random.gauss(0,1)\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Random Choices from Sequences\n", "\n", "We've mentioned the idea of lists when talking about loops and\n", "how we can loop through a sequence. We can also use lists\n", "to choose a random element from a predefined sequence using\n", "the `choice(seq)` function in the random module.\n", "\n", "Let's look at a simple example to replicate our coin flip\n", "from earlier:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "options = ['H', 'T']\n", "coin = random.choice(options)\n", "print(coin)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The previous example chose between strings, but\n", "we could just have easily given it numerical values" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "options = [-10, -1, -0.5, 0, 0.5, 1, 10, 100]\n", "result = random.choice(options)\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Debugging Random Code\n", "\n", "While nondeterminism is helpful for simulation,\n", "code that produces a different result each time\n", "can be difficult to debug (since the output is\n", "expected to change). Because these are actually\n", "pseudorandom numbers generated by an algorithm,\n", "there is almost always some number used to\n", "start the process called the *seed*. By default\n", "the seed is almost always based on some constantly\n", "changing value like time and date, but you can\n", "specify the seed by calling the `seed(a)` function\n", "in the random module where `a` is some integer.\n", "You would never want to do this when actually running\n", "a simulation because it loses the random nature,\n", "but it can be a sometimes be helpful if you are\n", "struggling to debug code with randomness." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example Application - Estimating Pi\n", "\n", "Let's look at an example known as Monte Carlo that\n", "uses randomness to estimate the value of $\\pi$\n", "(pretending we did not know the value of $\\pi$).\n", "\n", "Suppose we have a square of size $1 \\times 1$ that\n", "encloses a circle of radius 0.5 centered at (0.5, 0.5).\n", "If we generate random points inside the square,\n", "we can then check if they fall inside the circle by\n", "checking if\n", "$$(x-0.5)^2 + (y-0.5)^2 <= 0.5^2 $$\n", "The percentage of points inside the circle is then an\n", "estimate for the area of the circle. If we\n", "have an estimate for the area of\n", "the circle we can then recover an estimate for $\\pi$\n", "because \n", "$$A = \\pi r^2 \\implies \\pi = \\frac{A}{r^2}.$$\n", "Let's look at the code to do this:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = 10000\n", "radius = 0.5\n", "count_inside = 0\n", "for i in range(n):\n", " x = random.uniform(0,1)\n", " y = random.uniform(0,1)\n", " if (x-0.5)**2 + (y-0.5)**2 <= radius**2:\n", " count_inside += 1\n", "proportion_inside = count_inside / n\n", "pi = proportion_inside / radius**2\n", "print(pi)" ] } ], "metadata": { "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.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }