2

I am trying to generate a random array of 0s and 1s, and I am getting the error: shape mismatch: objects cannot be broadcast to a single shape. The error seems to be occurring in the line randints = np.random.binomial(1,p,(n,n)). Here is the function:

import numpy as np

def rand(n,p):
    '''Generates a random array subject to parameters p and N.'''

    # Create an array using a random binomial with one trial and specified
    # parameters.
    randints = np.random.binomial(1,p,(n,n))

    # Use nested while loops to go through each element of the array
    # and assign True to 1 and False to 0.
    i = 0
    j = 0
    rand = np.empty(shape = (n,n),dtype = bool)
    while i < n:
        while j < n:
            if randints[i][j] == 0:
                rand[i][j] = False
            if randints[i][j] == 1:
                rand[i][j] = True
            j = j+1
        i = i +1
        j = 0

    # Return the new array.
    return rand

print rand

When I run it by itself, it returns <function rand at 0x1d00170>. What does this mean? How should I convert it to an array that can be worked with in other functions?

4

2 に答える 2

4

そのすべてを経験する必要はありません。

 randints = np.random.binomial(1,p,(n,n))

0および1値の配列を生成し、

 rand_true_false = randints == 1

1s が に置き換えられ、 s が に置き換えられTrueただけで、別の配列が生成さ0Falseます。

于 2013-04-09T16:04:49.873 に答える