[英]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.我在 python 中为蒙特卡罗模拟创建了一个高级 Python 随机函数,我的代码运行正常。 However, I'm not able to generate a probability to draw: 2 - blue and 2 - purple balls out of 40 balls from a hat.
但是,我无法产生抽奖的概率:帽子上的 40 个球中有 2 个 - 蓝色和 2 个 - 紫色球。 Total balls are 40, 10-red, 10-blue, 10-Yellow, 10-Purple.
总球数为 40、10-红色、10-蓝色、10-黄色、10-紫色。 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% ?我的概率是 0.0% 怎么办?
Much appreciating for help.非常感谢帮助。
Your code is trying to represent colours in three different ways:您的代码试图以三种不同的方式表示颜色:
1, 2, 3, 4
1, 2, 3, 4
'1', '2', '3', '4'
'1', '2', '3', '4'
'blue', 'purple'
'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
.问题是,当您执行
drawing.count('purple')
它返回 0,因为drawing
不包含字符串'purple'
任何实例 - 它包含像'4'
这样'4'
字符串,因为那是您放入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.我还修复了
val += prob
行上的缩进 - 您应该在循环内执行此操作以累积每次采样的结果,而不仅仅是最后一次。
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.您的代码仍然存在其他逻辑问题 - 您最后只使用
N
进行除法,并且您的函数中有一些10
硬编码实例,但我不确定应该将哪个(些)更改为N
,也许40
应该以某种方式依赖于N
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.