【发布时间】:2013-04-01 03:47:02
【问题描述】:
我正在尝试生成一个由 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>。这是什么意思?我应该如何将它转换为可以在其他函数中使用的数组?
【问题讨论】:
-
你运行的是什么版本的 python 和 numpy?您上面发布的代码在
i = i +1...中只有一个错误的缩进... -
当你运行这个程序时它打印
<function rand at 0x1d00170>的原因是因为你的行print rand正在打印出函数对象。您需要改为调用该函数。试试:print rand(4,2)。