python模拟给定理论概率的实际发生次数

2024-09-24 02:18:30 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是模拟给定理论概率的实际发生次数

例如,6面有偏骰子的落地概率(1,2,3,4,5,6)为(0.1,0.2,0.15,0.25,0.1,0.2)。 掷骰子1000次,并输出模拟得到每个面的次数

我知道numpy.random.choices提供了生成每次滚动的功能,但我需要每个面的落地次数的摘要。 对于上述内容,Python的最佳脚本是什么


Tags: 功能numpy脚本内容目标random理论骰子
2条回答

也可以不用Numpy完成

import random
random.choices([1,2,3,4,5,6], weights=[0.1,0.2,0.15,0.25,0.1,0.2], k=1000)

Numpy可以轻松高效地完成以下任务:

faces = np.arange(0, 6)
faceProbs = [0.1, 0.2, 0.15, 0.25, 0.1, 0.2]        # Define the face probabilities
v = np.random.choice(faces, p=faceProbs, size=1000) # Roll the dice for 1000 times
counts = np.bincount(v, minlength=6)                # Count the existing occurrences
prob = counts / len(v)                              # Compute the probability

相关问题 更多 >