简体   繁体   中英

Can not generate probability for Monte Carlo Simulation in python 3.x?

I have created a high-level Python random function for a Monte Carlo Simulation in python and my code is running correctly. However, I'm not able to generate a probability to draw: 2 - blue and 2 - purple balls out of 40 balls from a hat. Total balls are 40, 10-red, 10-blue, 10-Yellow, 10-Purple. Following is my code:

import numpy as np
RED, BLUE, YELLOW, PURPLE = 1,2,3,4

def create_hat_of_balls(N):
    hat = 10*['1'] + 10*['2'] + 10*['3'] + 10*['4']
    val = 0 
    for num in range(40):
        drawing = [random.choice(hat) for num in range(10)]
        prob = drawing.count('blue') == 2 and drawing.count('purple') == 2
    val += prob
    final_prob = val / N
    print(f"(Blue, Purple) probability: {100*final_prob}%") 
    return hat

hat = create_hat_of_balls(10)
print(hat)

Result

(Blue, Purple) probability: 0.0%
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', 
'2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', 
'4', '4', '4', '4']

How my probability is 0.0% ?

Much appreciating for help.

Your code is trying to represent colours in three different ways:

  • As numbers 1, 2, 3, 4
  • As strings '1', '2', '3', '4'
  • As strings 'blue', 'purple'

The problem is that when you do drawing.count('purple') it returns 0, because drawing doesn't contain any instances of the string 'purple' - it contains strings like '4' , because that's what you put in hat .

You should choose one representation, and stick with it.

import numpy as np
RED, BLUE, YELLOW, PURPLE = 1, 2, 3, 4

def create_hat_of_balls(N):
    hat = [RED, BLUE, YELLOW, PURPLE] * 10
    val = 0 
    for num in range(40):
        drawing = [random.choice(hat) for num in range(10)]
        prob = drawing.count(BLUE) == 2 and drawing.count(PURPLE) == 2
        val += prob
    final_prob = val / N
    print(f"(Blue, Purple) probability: {100*final_prob}%") 
    return hat

hat = create_hat_of_balls(10)
print(hat)

I also fixed the indentation on the line val += prob - you should do this inside the loop to accumulate results from each sampling, instead of just the last one.

There are still other logical problems with your code - you are only using N to divide at the end, and there are some hard-coded instances of 10 in your function but I'm not sure which one(s) should be changed to N , and maybe the 40 should depend on N somehow too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM