def mysteryf_mean(n): x=5*rand(n) y=mysteryf(x) y_avg=mean(y) return y_avg
plot(rr2[:-1], rr2[1:], 'b.', ms=2.5, alpha=.7) title('random.rand Pair Wise Correlation'); # ### EX 2 # 1. Use Monte Carlo integration to average the function mysteryf in the mystery module by random sampling using numpy.random.rand over the interval [0, 5]. use numpy array operations to apply the mystery function f to all points xi and then use mean() use lots of point to get a good estimate. # # In[3]: from mystery import mysteryf # In[49]: mysteryf(array([0,1,2,3,4,5])) # In[44]: trails = 10000 results = empty([trails]) for i in xrange(npts): u = random.rand(100)*5 #array of size 100 in range (0->5) d = mysteryf(u).mean() # mean of that results[i] = d print "Average output of Mystery Function: ",mean(results) hist(results, bins=50); title('Mystery Function Average Output')
hist(x_rand,50) title('random.rand Histogram') figure (6) plot(x_rand[0::2],x_rand[1::2],'b.') title('random.rand Pairwise Correlation') xlabel('$x_i$') ylabel('$x_{i+1}$') #Part 2 - Finding the Mean of mysterf Using Monte Carlo Integration print "PART 2" from mystery import mysteryf x=5*rand(1000) y=mysteryf(x) figure (7) plot(x,y,'b.') title('Plotting mysteryf Evaluated at Random Points') xlabel('x') ylabel('mysteryf(x)') def mysteryf_mean(n): x=5*rand(n) y=mysteryf(x) y_avg=mean(y) return y_avg y_avg=mysteryf_mean(n) print "The mean of mysteryf in the range [0,5] is",y_avg