lundi 9 décembre 2019

How to generate iid sample from a given arbitrary probability density function

I want a function randgen(f, N) in python to generate N sample from a given pdf.

It's what I wrote:

import numpy as np
import matplotlib.pyplot as plt

def randgen(f,N, M=1):
    sample = M*np.random.random(N)
    y=[]
    sum = 0
    for x in sample:
      v = f(x);
      sum+=v;
      y.append(v)
    y = y/sum;
    return np.random.choice(sample, p=y, size=N)

def pp(x):
  return x**2

z = randgen(pp, 2000)
plt.hist(z)

It generates the following histogram for the function y=x^2. It seems working.

enter image description here

I have seen similar questions but without a clear reference to the function definition for randgen(f,N) which can takes arbitrary functions. I would like to know if my approach is correct or I missed a point.




Aucun commentaire:

Enregistrer un commentaire