如何使用np.random.randint()掷出n个骰子,注意到每个骰子都有一个潜在的不同面数,用一个向量f表示。

问题描述 投票:0回答:1

我正试图模拟单卷的 n 骰子,其中每个骰子都可能有 f 面。例如,如果𝑓=[2,5,7],则掷出3个2、5、7面的骰子。谢谢您!请问您是怎么想的?

python numpy random probability dice
1个回答
2
投票

你可以不用显式循环。 在这个例子中,我将使用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]])

0
投票

我用这个把它弄好了

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

谢谢你!

© www.soinside.com 2019 - 2024. All rights reserved.