Search code examples
pythonnumpyprobabilitydice

Build a function to roll a list of dice provided by `f`, and calculate the probability that the largest number among the outcomes is `x_max`


I have got up to this:

def largest_face(f, x_max):
    # inputs: f is a list of integers and x_max is an integer
    # output: a variable of type 'float'

    #generate len(f) random throws of (len(f)) dice with number of faces defined by f 
    outcomes= []
    for i in f:
        out = 1 + np.random.randint(i, size = len(f) )
        outcomes.append(out) #something wrong here as it works when testing separately but doesnt in the function, see below

    #calculate probabilty 
    proba = []
    for i in outcomes:
        if x_max >i:
            pass
        elif x_max<=i:
            a = x_max/i
            b =(x_max-1)/i
            c = a-b
            proba.append(c) 
    p=np.cumprod(proba)[-1]

    return p

However, while the two parts (generate outcomes and calculate probability) work well if run one by one, when I run the function it results in the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-af4c5a7929d0> in <module>
----> 1 c =largest_face([7,5],5)
      2 #c
      3 outcomes

<ipython-input-69-52e99563de50> in largest_face(f, x_max)
     13     proba = []
     14     for i in outcomes:
---> 15         if x_max >i:
     16             pass
     17         elif x_max<=i:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Any help would be appreciated!


Solution

  • The problem is your np.random.randint function. It actually returns an array of integers (refer to https://numpy.org/devdocs/reference/random/generated/numpy.random.randint.html)

    I tried to correct your implementation :

    import numpy as np
    def largest_face(f, x_max):
        # inputs: f is a list of integers and x_max is an integer
        # output: a variable of type 'float'
    
        #generate len(f) random throws of (len(f)) dice with number of faces defined by f 
        outcomes= []
        for i in f:
            out = 1 + np.random.randint(i, size = len(f) )
            outcomes.append(out) #something wrong here as it works when testing separately but doesnt in the function, see below
        #calculate probabilty 
        proba = []
        for array in outcomes:
          if x_max<=max(array):
                a = x_max/array
                b =(x_max-1)/array
                c = a-b
                proba.append(c) 
        p=np.cumprod(proba)[-1]
    
        return p
    if __name__=='__main__':
        print largest_face([7,5],5)