【问题标题】:How to use np.random.randint() to roll n dice, noting that each has a potentially different number of faces denoted by a vector f如何使用 np.random.randint() 掷 n 个骰子,注意每个骰子的面数可能不同,由向量 f 表示
【发布时间】:2020-09-25 17:48:19
【问题描述】:

我正在尝试模拟单掷 n 骰子,其中每个骰子都可能具有 f 面。例如,如果 ????=[2,5,7],则掷出三个具有 2、5 和 7 面的骰子。谢谢!

【问题讨论】:

  • similar though not identical question 的答案可能会有所帮助。
  • 谢谢丹尼斯,但不幸的是,这个问题并没有解决我的问题,即为面部向量生成随机滚动。
  • 这需要遍历一个列表,生成一个指定范围内的随机数,然后相加。这些都是相当简单的操作。其中有一个你不知道该怎么做吗?或者你不知道如何组合它们?

标签: python numpy random probability dice


【解决方案1】:

你可以在没有显式循环的情况下做到这一点。在此示例中,我将使用 numpy 1.17 中引入的“新”numpy 随机 API。在新的 API 中,随机整数是使用生成器的integers 方法生成的;它对应于旧的randint 方法:

In [22]: rng = np.random.default_rng()                                          

In [23]: f = np.array([2, 5, 7])                                                

In [24]: rng.integers(1, f + 1)                                                 
Out[24]: array([2, 4, 6])

要在一次调用中重复该过程n 次,请使用size 参数:

In [30]: n = 8                                                                  

In [31]: rng.integers(1, f + 1, size=(n, 3))                                    
Out[31]: 
array([[1, 3, 4],
       [1, 1, 5],
       [1, 3, 1],
       [2, 3, 1],
       [2, 2, 4],
       [2, 4, 2],
       [1, 1, 3],
       [2, 1, 7]])

【讨论】:

    【解决方案2】:

    我得到了它的工作:

        f=[3,4,5]
        outcomes= []
        for i in f:
            out = 1 + np.random.randint(i, size = len(f) )
            outcomes.append(out)
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 2013-10-09
      • 1970-01-01
      • 2018-04-14
      • 2018-09-08
      • 1970-01-01
      • 2017-01-16
      • 2017-04-09
      • 2013-09-17
      • 2021-09-09
      相关资源
      最近更新 更多