Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Random numbers What does it mean for a number to be random?"— Presentation transcript:

1 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.

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

3 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

4 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))

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

6 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

7 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

8 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 = , c = 11 GNU C++: m = 232, a = , 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

9 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 = c = m = 2**32 prevList = simpleRNG(n-1,initSeed) # Get list so far num = (a * prevList[-1] + c) % m # Compute next number return prevList + [num]

10 Using our pseudo RNG… simpleRNG(5,0) [0, , , , , ] simpleRNG(5,100) [100, , , , , ] simpleRNG(5,42) [42, , , , , ] X0 is usually discarded Notice… you get a different sequence of numbers depending on the seed value (X0 is usually ignored.)

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

12 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 [ , , , , ] What converstion can we apply to generate a random roll of a single die? [x % for x in simpleRNG(6,0)] [1, 4, 3, 2, 5, 2]

13 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 ?

14 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()

15 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.

16 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 # 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?

17 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?

18 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…

19

20 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:


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

Similar presentations


Ads by Google