【问题标题】:python simulation of actual number of occurrence given theoretical probabilitiespython模拟给定理论概率的实际发生次数
【发布时间】:2021-11-08 23:30:57
【问题描述】:

目标是在给定理论概率的情况下模拟实际发生次数。

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

我知道 numpy.random.choices 提供生成每个滚动的功能,但我需要每个面的着陆次数的摘要。 上面使用 Python 的最佳脚本是什么?

【问题讨论】:

  • 总结来说,collections.Counter 可能是最好的。对于滚动,random.choices 应该可以工作,不需要 numpy。
  • 欢迎来到 Stack Overflow。请阅读How to Askmeta.stackoverflow.com/questions/261592/…。在寻找工具或库函数时,了解事物的专有名称会有所帮助。例如,你知道什么是直方图吗?

标签: python numpy data-science simulation probability


【解决方案1】:

不用 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)

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

    • 仅供参考:v 仅包含小的正整数,因此histogram 的有效替代方案是bincount
    • @WarrenWeckesser 确实如此。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多