2

我正在尝试生成一个由 0 和 1 组成的随机数组,但出现错误:形状不匹配:无法将对象广播到单个形状。该错误似乎发生在该行中randints = np.random.binomial(1,p,(n,n))。这是功能:

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

当我自己运行它时,它会返回<function rand at 0x1d00170>. 这是什么意思?我应该如何将它转换为可以在其他函数中使用的数组?

4

2 回答 2

4

你不必经历这一切,

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

产生你的数组01值,

 rand_true_false = randints == 1

将产生另一个数组,只是将1s 替换为sTrue0s替换为False

于 2013-04-09T16:04:49.873 回答
1

显然,@danodonovan 的答案是最 Pythonic 的,但如果你真的想要更类似于循环代码的东西。这是一个更简单地修复名称冲突和循环的示例。

import numpy as np

def my_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.

    randBool = np.empty(shape = (n,n),dtype = bool)
    for i in range(n):
        for j in range(n):
             if randInts[i][j] == 0:
                randBool[i][j] = False
             else:
                randBool[i][j] = True

    return randBool


newRand = my_rand(5,0.3)
print(newRand)
于 2013-04-09T16:21:18.713 回答