Random numbers What does it mean for a number to be random?

Slides:



Advertisements
Similar presentations
The Random Class.
Advertisements

Modular Programming With Functions
Building Java Programs
Random variables 1. Note  there is no chapter in the textbook that corresponds to this topic 2.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.1 Chapter 5 Loops.
HW 4 EECS 110.
Exercise 4 1. Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the.
Mathematics in Today's World
Pseudorandom Number Generators
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
Random numbers in Python Nobody knows what’s next...
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
Chapter 11: understanding randomness (Simulations)
Copyright © 2010 Pearson Education, Inc. Unit 3: Gathering Data Chapter 11 Understanding Randomness.
IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to.
CSCE 2100: Computing Foundations 1 Probability Theory Tamara Schneider Summer 2013.
MOM! Phineas and Ferb are … Aims:
STAT115 STAT225 BIST512 BIO298 - Intro to Computational Biology Python Tutorial II Monty Python, Game of Life and Sequence Alignment Feb 1, 2011 Daniel.
Module 1: Statistical Issues in Micro simulation Paul Sousa.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Monte Carlo Methods.
Chapter 9 Review. 1. Give the probability of each outcome.
Basic Concepts of Probability Coach Bridges NOTES.
CS 121 Today Fractals and Turtles! The Koch Curve how random…
1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
Computer simulation Sep. 9, QUIZ 2 Determine whether the following experiments have discrete or continuous out comes A fair die is tossed and the.
Random numbers in C++ Nobody knows what’s next....
1 1 Slide © 2004 Thomson/South-Western Simulation n Simulation is one of the most frequently employed management science techniques. n It is typically.
Controlling Program Flow with Decision Structures.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
AP Statistics From Randomness to Probability Chapter 14.
Arrangements and Selections (and how they may be counted)
CS 121 Today Fractals and Turtles! The Koch Curve how random…
11-2 Basic Probability.
Adding Probabilities 12-5
Monte Carlo Methods Some example applications in C++
Recap: If, elif, else If <True condition>:
Chapter 11 Probability.
Building Java Programs
Random Bricks.
Thinking Critically 1.1 An Introduction to Problem Solving
Monte Carlo simulation
Number guessing game Pick a random number between 1 and 10
LOOPS.
Random numbers Taken from notes by Dr. Neil Moore
Writing Functions( ) (Part 5)
Understanding Randomness
Random numbers What does it mean for a number to be random?
The Math class The java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square.
Probability 14.1 Experimental Probability 14.2 Principles of Counting
Coding Concepts (Basics)
Honors Statistics From Randomness to Probability
Building Java Programs
Dry run Fix Random Numbers
CS 188: Artificial Intelligence
Section 7.1 Sampling Distributions
Loop Strategies Repetition Playbook.
Conditional and iterative statements
Understanding Randomness
11-2 Basic Probability.
Lecture 2 Binomial and Poisson Probability Distributions
Computer Science I: Get out your notes.
Understanding Randomness
Statistics and Probability-Part 5
Data Structures and Algorithm Analysis Hashing
IST256 : Applications Programming for Information Systems
Lecture 9 Randomized Algorithms
Random numbers What does it mean for a number to be random?
Presentation transcript:

Random numbers What does it mean for a number to be random? A number that is drawn from a set of possible values, each of which is equally probable Many practical uses: Computer games Simulation of natural phenomena Cryptography Art, Music Etc… any problem where you want to produce an unpredictable result! Random Numbers What does it mean to have a random number? For example, if you want a random number between 1 and 6 (say like when rolling a die) it means each number comes up with probability 1/6. This does not mean that you will get the numbers 1-6 every 6 times you roll the die. It means that over the long run each of the numbers 1-6 will turn up 1/6 of the time. But you might have three 2’s in a row.

The random module Thankfully, you don't have to implement your own RNG import random from random import *

Some random functions… choice(myList) chooses 1 element from the sequence myList choice(['Harris', 'McDonnell', 'Larison']) How would you get a random int from 0 to 9 inclusive? randint(low,hi) chooses a random int from low to hi, inclusive

Throw a coin n times … from random import * def flipCoins(n = 20): mapping = ['H', 'T'] flipList = [ mapping[randint(0,1)] for flip in range(n) ] print(''.join(flipList))

This will do the same… from random import * def flipCoins(n = 20): flipList = [ choice([‘H’, ‘T’]) for flip in range(n) ] print(''.join(flipList))

Randomness vs. Determinism Are there random numbers? Can a computer generate them? RNG Pseudo-randomness Think for a second: how can a computer generate a random number? Computers follow a predefined sequence of instructions, there is nothing random about it – you run the same program with the same input, then you get the same result. How can computers simulate random events? Computers use functions to generate random numbers. So they are not actually random. That is why they are called pseudorandom. A “black box” model of a random number generator. Output

Randomness vs. Determinism Are there random numbers? Can a computer generate them? Not without help! RNGs are pseudo-random They generate a fixed sequence of numbers based on a recurrence equation The RNG revealed. Output http://en.wikipedia.org/wiki/Mersenne_twister

How? One of the most common and well-known methods involves a sequence generating function: Most RNGs use this formula, varying only the choice of a, c and m! Example: Java: m = 248, a = 25214903917, c = 11 GNU C++: m = 232, a = 1103515245, c = 12345 The sequence of numbers generated depends on a, c and m… …and on the choice of the first value in the sequence, X0. Called the seed value

We can implement our own RNG! The GNU C++ RNG implemented in Python! def simpleRNG(n,initSeed): """ Generate a list of n random numbers in a sequence. n must be at least 1. initSeed can be any value you want """ if n <= 0: # Return seed for X0 return [initSeed] a = 12345 c = 1103515245 m = 2**32 prevList = simpleRNG(n-1,initSeed) # Get list so far num = (a * prevList[-1] + c) % m # Compute next number return prevList + [num]

Using our pseudo RNG… simpleRNG(5,0) [0, 1103515245, 362951858, 2093312527, 228441028, 3709459729] simpleRNG(5,100) [100, 1104749745, 2717952470, 1942241043, 3561744808, 3262960853] simpleRNG(5,42) [42, 1104033735, 2468743612, 655472969, 1198931886, 1460345899] X0 is usually discarded Notice… you get a different sequence of numbers depending on the seed value (X0 is usually ignored.)

Getting useful numbers Clearly, we need to get the numbers into a useful range depending on our simulation Consider dice…

Suppose we wanted to simulate 6 random rolls of a single die Using your first RNG Suppose we wanted to simulate 6 random rolls of a single die [1103515245, 362951858, 2093312527, 228441028, 3709459729 1104749745] What converstion can we apply to generate a random roll of a single die? [x % 6 + 1 for x in simpleRNG(6,0)] [1, 4, 3, 2, 5, 2]

Some random programs… from random import choice def guess( myNum ): """ guesses the user's #, "hidden" """ compGuess = choice(range(1,101)) if compGuess == myNum: print('I got it!') else: return guess( myNum ) run guess1() – notice how lame this is. No idea what guesses were taken, nor how many guesses it took to make print guesses ? num guesses ?

The final version from random import * import time def guess(hidden): """ guesses the user's hidden # """ compguess = choice(range(1, 101)) # print ('I choose', compguess) # time.sleep(0.05) if compguess == hidden: # at last! # print ('I got it!') return 1 else: return 1 + guess(hidden) run guess2()

Monte Carlo Methods Any method which solves a problem by generating suitable random numbers, and observing the fraction of numbers obeying some property (or properties) The method is useful for obtaining numerical solutions to problems which are too complicated to solve analytically. http://mathworld.wolfram.com/MonteCarloMethod.html

Monte Carlo in action How many doubles will you get in n rolls of 2 dice? the input n is the total number of rolls def countDoubles(n): """ inputs a # of dice rolls outputs the # of doubles """ if n == 0: return 0 # zero rolls, zero doubles… else: d1 = choice([1,2,3,4,5,6]) d2 = choice(range(1,7)) if d1 != d2: return countDoubles(n-1) # don't count it return 1 + countDoubles(n-1) # COUNT IT! one roll where is the doubles check?

Write the same function with Monte Carlo in action Write the same function with a list comprehension def countDoubles(n): """ inputs a # of dice rolls outputs the # of doubles """ return sum([choice(range(6)) == choice(range(6)) \ for x in range(n)]) Run countDoubles(2) where is the doubles check?

One final example… Suppose you wanted to estimate pi Generate two random numbers between -1 and 1. denoted (x,y) Compute the distance of (x,y) from (0,0) Depending on distance, point is either inside or outside of a circle centered at (0,0) with a radius of 1. llustration…

Quiz Design a strategy for estimating pi using random numbers ("dart throws") and this diagram ("dartboard"): Name(s): (1,1) What does this return? 1) Here is a dart-throwing function: def throw(): return [ random.uniform(-1,1), random.uniform(-1,1) ] 2) Here is a dart-testing function: What does this return? (-1,-1) def test(x,y): return (x**2 + y**2) < 1.0 3) What strategy could use the functions in (1) and (2) to estimate pi? 4) Write a function to implement your strategy: