lecture will start at 10:40. as usual, lecture will be recorded ...non-deterministic outcome of a...

20
Welcome to CS 2 Lecture will start at 10:40. As usual, lecture will be recorded . If you have any question, please ask in the chat. 1

Upload: others

Post on 20-Feb-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

  • Welcome to CS 2

    • Lecture will start at 10:40.• As usual, lecture will be recorded.• If you have any question, please ask in the chat.

    1

  • 5: RandomNumbers and Simulations

  • Today• Random numbers‣What? How?‣Python module: random

    • Computer simulations• Homework 3‣Dice simulation‣Tournament simulation

    3

  • Random Number• Random number‣ A number “chosen” randomly (in a set of values)‣ Example: Throwing a dice random number in {1,…,6}

    • Random number generator (RNG)‣ “Device that generates a sequence of numbers or symbols that

    cannot be reasonably predicted …”• Pseudorandom number generator (PRNG)‣ Algorithm that deterministically generates random numbers!‣ Contradiction?

    4

    https://en.wikipedia.org/wiki/Random_number_generationhttps://en.wikipedia.org/wiki/Pseudorandom_number_generator

  • PRNG Idea• Use “complex” formulas to generate sequence

    of numbers that looks random• Example: LCG (Linear congruential generator)

    𝑋𝑋𝑛𝑛+1 = 𝑎𝑎 ∗ 𝑋𝑋𝑛𝑛 + 𝑏𝑏 𝑚𝑚𝑚𝑚𝑚𝑚 𝑚𝑚𝑋𝑋0 = 𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑎𝑎𝑖𝑖 𝑣𝑣𝑎𝑎𝑖𝑖𝑣𝑣𝑣𝑣

    with large 𝑎𝑎, 𝑏𝑏, 𝑚𝑚.

    5

  • Why Random Number• Applications of random numbers‣ Simulations of non-deterministic events‣ Cryptography: generating keys‣ Games: generating levels, AI players, …‣ …

    6

  • Random Number in Python• random module (doc)• random.random() function‣ Generates random floating number in [0, 1)

    ‣ Can also be used to generate “other random numbers” y is a random number in [5, 15)

    d is a random value in {1, …, 6}7

    import random

    x = random.random() # returns a random number# between 0 and 0.9999…

    y = 10 * random.random() + 5

    d = int(6 * random.random()) + 1

    https://docs.python.org/3/library/random.html

  • Random Number in Python• Many (useful) functions in random module‣ random.randint(a,b) random integer N with a ≤ N ≤ b‣ random.choice(L) random element from the list L‣ random.gauss(mu, sigma) sample of a Gaussian distribution‣ random.shuffle(L) shuffle the list L ‣ …

    • Initialization of the PRNG‣ random.seed(n) Initialize the generator with the given seed‣ Extremely useful to reproduce experiments!

    8

  • ComputerSimulations

  • Computer Simulation• Computer simulations (wiki)‣Useful to analyze complex systems‣May replace/confirm costly experiments‣May be used for prediction (e.g. weather forecast)‣…

    • Often based on random simulations‣Simple example: Throwing a die

    • Model-based simulations‣bad model bad simulations incorrect conclusions!10

    https://en.wikipedia.org/wiki/Computer_simulation

  • Dice Simulation

    11

    import random # Module needed to generate "random" numbersrandom.seed(123)

    def one_dice(nb_simulations):counter = [0,0,0,0,0,0] # shorter version: counter = [0]*6

    for i in range(nb_simulations):x = random.randint(1,6) # Throw a dice and get a random (uniform) resultcounter[x-1] += 1 # Be careful x is in {1,...,6}, but lists are indexed from 0

    print("Raw values:", counter)

    for i in range(6):# Compute percentage and round with 2 digits after the decimal pointcounter[i] = round( counter[i] * 100 / nb_simulations, 2)

    print("Percentage values:", counter) # slightly different in Google Colab Notebook

    # Run the simulationone_dice(10000)

  • Homework 3 – Part 1• Write a new function two_dice(nb_sims) that simulates

    throwing two dice and compute the sum of the dice values.• Print the percentage of time each sum is obtained (sum can

    be 2, 3, 4, …, 12).

    • Submit on OCWi before next lecture (Jan 25, 10:40).‣ Submit only two_dice function (I do not need the whole notebook)‣ 5 points

    12

  • TournamentSimulation

  • Tournament Simulation• Motivation‣Let's simulate a tournament and estimate the winning chance of each player‣Not always the best players in top positions

    • Questions‣ Is it normal/usual?‣ Is it possible to be lucky (and win while being weaker)? Let's try to find out with computer simulations!

    14

  • Tournament Model• Tournament‣32 players‣Single-elimination bracket (loss eliminated) (wiki)‣ Initial random allocation of players‣Third place playoff for semifinals losers (wiki) Four top players win points; 100, 60, 30, 10 points

    • Players‣Random strength in {0,…,100}‣Stronger player always wins against weaker players

    15

    Adrian

    Kevin

    Lisa

    Scott

    Bert

    Zaphod

    Drew

    Ernie

    Michelle

    Andrew

    Johan

    Ian

    Monica

    Steve

    Red

    Robert

    Kevin

    Lisa

    Zaphod

    Ernie

    Lisa

    Ernie

    Andrew

    Ian

    Monica

    Robert

    Andrew

    Robert

    https://en.wikipedia.org/wiki/Single-elimination_tournamenthttps://en.wikipedia.org/wiki/Third_place_playoff

  • Player Generation

    16

    # generate_players_strength.py# I use this file to generate 32 players

    import randomrandom.seed(2021) # Fix the PRNG seed for reproducibility

    NB_PLAYERS = 32 # Number of playersSTRENGTH = [] # Array (list) to store the strength of each player

    # Generate random strength for each playerfor _ in range(NB_PLAYERS): # _ can be used when the index is not used

    s = random.randint(0, 100) # obtain a random strength between 0 and 100 (incl.)STRENGTH.append(s)

    print(STRENGTH)# [51, 80, 69, 35, 31, 81, 4, 56, 60, 73, 8, 40, 34, 37, 60, 9, 20, 21, 6, 95, 13, 86, 91, 70, 37, 6, 68, 87, 59, 14, 25, 77]

    STRENGTH = [random.randint(0,100) for _ in range(NB_PLAYERS)] # shorter version# This is called list comprehension; specific to Python!

  • Tournament

    17

    # tournament.py# Global variablesNB_PLAYERS = 32STRENGTH = [51, 80, 69, 35, 31, 81, 4, 56, 60, 73, 8, 40, 34, 37, 60, 9, 20, 21, 6, 95, 13, 86, 91, 70, 37, 6, 68, 87, 59, 14, 25, 77]

    def compute_winner(player1, player2):""" Compute the winner in a match between two players."""

    def simulate_tournament():""" Simulate a tournament with all NB_PLAYERS players1) Generate a random bracket2) Simulate the competition3) Return the identities of the players ranked 1 to 4"""

    def compute_stats(nb_simu):""" Compute statistics based on nb_simu tournaments."""

  • Homework 3 – Part 2• Tournament model‣Stronger player always wins against weaker players‣Unrealistic assumption Let's try to improve the model

    • Non-deterministic outcome of a game:‣Player1 with strength S1 versus Player2 with strength S2:

    P1 wins with proba. 𝑆𝑆1𝑆𝑆1+𝑆𝑆𝑆

    and P2 wins with proba. 𝑆𝑆𝑆𝑆𝑆1+𝑆𝑆𝑆

    ‣Example: Player of strength 30 wins 1/3 of the games vs a player of strength 60

    18

  • Homework 3 – Part 2• Write a new function compute_winner(p1, p2) that

    computes a winner according to the probabilities given on previous slide.

    • Using the same set of players' strength, simulate the average points earned by each player under this new model.

    • Submit on OCWi before next lecture (Jan 25, 10:40).‣ Submit only compute_winner function‣ 10 points

    19

  • Advanced Remarks• Using only random.random(), how to implement

    a function similar to:‣random.choice(L) (not too difficult)‣random.shuffle(L) (much more difficult)‣random.gauss(…) (math question, not CS question)

    • Check the source code of random module

    20

    import randomimport inspect

    code = inspect.getsource(random.shuffle)print(code)

    Welcome to CS 25: Random�Numbers and SimulationsTodayRandom NumberPRNG IdeaWhy Random NumberRandom Number in PythonRandom Number in PythonComputer�SimulationsComputer SimulationDice SimulationHomework 3 – Part 1Tournament�SimulationTournament SimulationTournament ModelPlayer GenerationTournamentHomework 3 – Part 2Homework 3 – Part 2Advanced Remarks