pythonloopssimulationgambling

First steps in a Monte Carlo simulator


I'm working on a simple monte carlo simulator to look at the probability of reaching a goal before going broke. The plan was to create a function that first checks if the fortune has reached the goal, and if not, generates random numbers, compares them to a chosen probability value, and moves the fortune up and down depending on whether the gambler won or lost. I want this function to return a list of 100 ones and zeros, but instead I'm getting k + or - 1. What am I doing wrong here? Also, how can I make this cleaner?

import numpy as np
from numpy import random

# Variables
k = 5              #starting fortune
g = 10             #goal. Amount of money at which the gambler stops playing. 
p = .5             #probability of winning
bet = 1            #bet size

def goal_or_bust(set_size=100):
    global k
    made_goal = []
    for i in range(set_size):
        
        
        if k <= 0:
            made_goal.append(0) 
            break
            
        elif k >= g:
            made_goal.append(1)
            break
            
        else:
            rand01 = np.random.rand()
            if rand01 <= p:
                k = k + bet
                return(k)
            if rand01 > p:
                k = k - bet
                return(k)
            
    return(made_goal)    
            
goal_or_bust()

Solution

  • You are exiting your function immediately after testing for your outcome.

            rand01 = np.random.rand()
            if rand01 <= p:
                k = k + bet
                return(k) # <<<< HERE
            if rand01 > p:
                k = k - bet
                return(k) # <<<<< HERE
    

    So your for loop only goes around (iterates) once.

    As for cleaning up your code, remove your global variables and make them all parameters to your function.