lundi 18 janvier 2021

How to sample from a given probability distribution?

I am plotting a histogram with the same probability distribution of particle in a ground state one dimensional box, using random numbers. But when compared with the original distribution, the values are getting cut at the top.

Here is the code

from numpy import*
from matplotlib.pyplot import*

lit=[]
def f(x):
    return 2*(sin(pi*x)**2)
for i in range(0,10000):
    x=random.uniform(0,1)
    y=random.uniform(0,1)
    if y<f(x):
        lit.append(x)

l=linspace(0,1,10000)
hist(lit,bins=100,density=True)
plot(l,f(l))
show()

The graph produced is: enter image description here

How to improve this code to match the original?




Aucun commentaire:

Enregistrer un commentaire