2015-02-14 02:36:41
0
I generate a random sample from the two dimensional distribution, But I got this run time error. Could someone tell me how to fix this error?
This is the error message:
ValueError Traceback (most recent call last)
in ()
25 # Do the accept/reject comparison
26 if x < P(x,y):
---> 27 samples[accepted] = x,y
28 accepted += 1
29
ValueError: setting an array element with a sequence.
P = lambda x, y: np.exp(-x**2-y**2-x**2*y**2)
# domain limits
xmin = -2 # the lower limit of our domain
xmax = 2 # the upper limit of our domain
# range limit (supremum) for y
ymin = -2
ymax = 2
N = 10000 # the total of samples we wish to generate
accepted = 0 # the number of accepted samples
samples = np.zeros(N)
count = 0 # the total count of proposals
# generation loop
while (accepted < N):
# pick a uniform number on [xmin, xmax) (e.g. 0...10)
x = np.random.uniform(xmin, xmax)
# pick a uniform number on [0, ymax)
y = np.random.uniform(ymin,ymax)
# Do the accept/reject comparison
if x < P(x,y):
samples[accepted] = x,y
accepted += 1
count +=1
print count, accepted
# get the histogram info
hinfo = np.histogram(samples,30)
# plot the histogram
plt.hist(samples,bins=30, label=u'Samples', alpha=0.5);
# plot our (normalized) function
xvals=np.linspace(xmin, xmax, 1000)
plt.plot(xvals, hinfo[0][0]*P(xvals), 'r', label=u'P(x)')
# turn on the legend
plt.legend()