# Physique Numerique M1 : TD 2 - Exercice 3 ## Generate random
Transcription
# Physique Numerique M1 : TD 2 - Exercice 3 ## Generate random
# Physique Numerique M1 : TD 2 - Exercice 3 ## Generate random numbers with a Gaussian distribution ## using the Metropolis algorithm. from pylab import * def gauss(v): # Gaussian distribution g=exp(-(v-mu)**2/(2*sig**2))/(sqrt(2*pi)*sig) return g def dist(a,b): # ratio of probabilities c=gauss(a)/gauss(b) return c print "Entrer le nombre de pas pour la chaine de Markov:" M = input() print "Choisir le deplacement maximal (<=1) par pas:" delta = input() res=zeros([M]) sig=0.05 mu=0.5 # variance of the Gaussian distribution # mean of the Gaussian distribution x0=random() # start with a random number res[0]=x0 counter=0. for i in xrange(M): xt=random() # choose another random number x=x0+(2*xt-1.)*delta-floor(x0+(2*xt-1.)*delta) # decide whether to ... if dist(x,x0)>=random(): # ... accept the new number res[i]=x # & append to the list x0=x counter+=1. # or ... else: res[i]=x0 # keep the old number # & append to the list t=arange(0,1,0.01) plot(t,gauss(t)) # plot the Gaussian distribution hist(res,bins=100,normed=True) # plot the histogram of the array of random numbers show() print 'moyenne:', sum(res)/M print 'variance:', sqrt(sum(res**2)/M-(sum(res)/M)**2) print 'pourcentage des pas acceptes:', counter/M*100