Simple Monte Carlo Simulation in python

python monte carlo simulation finance
plot monte carlo simulation || python
monte carlo simulation python pdf
monte carlo simulation python github
monte carlo python github
monte carlo simulations with python (part 2)
monte carlo simulations with python (part 3)
monte carlo simulation example

What is the expectation of the number of times you need to roll a fair die until you have seen every number?

I have been asked to define a function that runs a monte carlo simulation that returns an estimate for the question above. My understanding of the solution is that I need to:

  1. Define a function that takes the number of trials as an input
  2. Generates a random integer between 1 and 6 (the number of sides on a die)
  3. Store that integer in a list if it is not already in the list
  4. Count the number of trials it takes to reach said condition, and return that count

I am fairly new to programming and Python in particular so I am struggling to identify why my syntax does not produce an output when the function is called and was hoping someone could help steer me in right direction

This is my code :

def roll(n=1000):
    trials = []
    sides = 6
    start = 1

    for i in range (n):
        for x in range (sides):
            collection = [random.randint(1,sides)]
            while any([x not in collection]):
            collection.append(random.randint(1,6))
            trials.append(len(collection))

    return sum(trials)/ len(trials)

You are probably not printing whatever the funtion returns - that why it displays nothing.

Use print(roll()) instead of roll() to print the result you get.

You have too many loops and your solution uses far too much memory space.

Consider being unlucky and having to roll 1.000.000.000.000 times to get the first 6 - you'll save 1.000.000.000.000 other numbers in a list .. thats a lot of memory.


You can use a set to remember seen numbers and a counter to count how long it took to find all:

def roll(sides=6, n=1000):
    """Tests 'n' times to roll all numbers from 1 to 'sides' randomly.
    Returns average tries needed to see all numbers over 'n' tries."""
    trials = []   # collects all sinly tried counters

    for _ in range(n):
        seen = set()   # empty, will only ever store 6 elements at most
        tried = 0      # how long did it take to find all 6?
        while len(seen) < sides:  # use sides here as well
            seen.add(random.randint(1,sides))
            tried += 1
        trials.append(tried)

    return sum(trials)/n


print(roll())  

Output (4 starts):

14.878

14.694

14.732

14.516

Monte Carlo Simulations with Python (Part 1), This is the first of a three part series on learning to do Monte Carlo simulations with Python. This first tutorial will teach you how to do a basic� Monte Carlo’s can be used to simulate games at a casino (Pic courtesy of Pawel Biernacki) This is the first of a three part series on learning to do Monte Carlo simulations with Python. This first tutorial will teach you how to do a basic “crude” Monte Carlo, and it will teach you how to use importance sampling to increase precision.

Your while condition does not express what you expect it to be. You probably wanted to use list comprehension

while any([x not in collection for x in [1, 2, 3, 4, 5, 6])

also, you don't want 3 layers of loop, only two: one for each trial and the other while trial is not complete. A working example, close to your original post would be

 import random

 def roll(n=1000):
     trials = []
     sides = 6
     start = 1
     possible_sides = [1, 2, 3, 4, 5, 6]

     for i in range (n):
         collection = [random.randint(1,sides)]
         while any([side not in collection for side in possible_sides]):
             collection.append(random.randint(1,6))
         trials.append(len(collection))

     return sum(trials)/ len(trials)

whereas a more efficient solution uses set to efficiently do the same thing as the previous solution achieves with any([side not in collection for side in possible_sides]):

import random

 def roll(n=1000):
     trials = []
     sides = 6
     start = 1
     possible_sides = set([1, 2, 3, 4, 5, 6])

     for i in range (n):
         n_rolls = 0
         sides_rolled = set()
         while not sides_rolled == possible_sides:
             sides_rolled.add(random.randint(1, sides))
             n_rolls += 1

         trials.append(n_rolls)

     return sum(trials)/ len(trials)

Or, even more efficiently, just check if len(sides_rolled) < 6, as pointed out in an answer by Patrick Artner.

Monte Carlo Introduction, Monte Carlo Simulation and Python 1 - Intro It is easy to fall into the trap of thinking that on Duration: 7:09 Posted: Feb 11, 2015 Monte Carlo simulation in Python. A Monte Carlo simulation is basically any simulation problem that somehow involves random numbers. Let’s start with an example of throwing a die repeatedly for N times. We can simulate the process of throwing a die by the following python code,

You can simplify your code considerably by using a set instead of a list and also changing your iteration logic:

import random

def roll_till_all_sides_appeared():
    sides_seen = set()
    n = 0

    while len(sides_seen) < 6:
        side = random.randint(1, 6)
        sides_seen.add(side)         # will only be added if it isn't present
        n += 1

    return n

def test(repetitions):
    max_n = float('-inf')
    min_n = float('inf')
    sum_n = 0

    for _ in range(repetitions):
        n = roll_till_all_sides_appeared()
        max_n = max(max_n, n)
        min_n = min(min_n, n)
        sum_n += n

    print('max:', max_n)
    print('min:', min_n)
    print('avg:', sum_n / repetitions)

This code can be used like this:

>>> test(10)
max: 32
min: 8
avg: 14.3
>>> test(100)
max: 45
min: 6
avg: 14.13
>>> test(1000)
max: 56
min: 6
avg: 14.749
>>> test(10000)
max: 62
min: 6
avg: 14.6422

Monte Carlo Simulation and Python 1 - Intro, A simple 50/50 strategy, a martingale strategy, and the d'alembert strategy. We use the Duration: 7:09 Posted: Mar 19, 2014 Welcome to the monte carlo simulation experiment with python. Before we begin, we should establish what a monte carlo simulation is. The idea of a monte carlo simulation is to test various outcome possibilities.

A Random Walk & Monte Carlo Simulation || Python Tutorial || Learn , A Random Walk & Monte Carlo Simulation || Python Tutorial || Learn Python Programming Duration: 7:54 Posted: Mar 6, 2017 Monte Carlo Simulator for Pandas Series pandas-montecarlo is a lightweight Python library for running simple Monte Carlo Simulations on Pandas Series data. Changelog »

Monte Carlo Methods — Computational Statistics in Python 0.1 , We can still use the inverse transform method to create a random number generator The basic idea of Monte Carlo integration is very simple and only requires� For all its successes and fame, the basic idea is deceptively simple and easy to demonstrate. We demonstrate it in this article with a simple set of Python code. The idea A tricky integral. While the general Monte Carlo simulation technique is much broader in scope, we focus particularly on the Monte Carlo integration technique here.

Monte Carlo Simulation: Definition, Example, Code, The easy answer is “I run it in Multicharts”, I click Monte Carlo — but I decided to try to explain my Python code. I got so wrapped up in it, by the� Monte Carlo Simulator for Pandas pandas-montecarlo is a lightweight Python library for running simple Monte Carlo Let’s run a monte carlo simulation on the

Comments
  • Your original post is not properly indented: The while should have at least one line indented after it.
  • What do you mean by "does not produce an output when the function is called " ? How are you invoking/calling the function?
  • @qu yes, but if you use it you need to use it throughout - and it is not needed for the task as formulated: YAGNI
  • @Q you introduce a variable that you do not need. If you wanted to have it variable, I would use def roll(n=1000,sides=6) - this would give you the same readability but also make clear that this is used to calculate it for other sided dice as well ... and add docstring etc.
  • In the case of the code from the OP, sides is an explaining variable, ie it answers the question: "What is that number 6 doing?" (You had a bare 6 in a previous edit)
  • for _ in range(1000) should probably be for _ in range(n). Otherwise n is not needed at all. You can also use it instead of len(trials), because if that is not n something went seriously wrong...
  • @Graipher Thanks .. some blunders there after the last edit
  • **while not sides_rolled == possible_sides: sides_rolled.add(random.randint(1, sides)) ** the "not" accomplishes the same thing as **while sides_rolled != possible_sides, then adds the result to the set and counts the number of rolls? Also, the .add is a specifc syntax for the set type that accomplishes the same thing as append?
  • Thank you for this solution. Very helpful
  • Yes, I could've written sides_rolled != possible_sides and it would perhaps be considered better. Honestly I was typing out rather quick and missed some possible idiosyncrasies. In general, as pointed out in other comments, checking the length of sides_rolled is sufficient, and set equality adds unnecessary overhead.