我正在尝试生成一个由 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>
. 这是什么意思?我应该如何将它转换为可以在其他函数中使用的数组?