Reputation: 451
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.
Upvotes: 0
Views: 146
Reputation: 51037
Your code is trying to represent colours in three different ways:
1, 2, 3, 4
'1', '2', '3', '4'
'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.
Upvotes: 1