# How to generate samples from an arbitrary continuous pdf?

If I define an arbitrary pdf p[x_] for a arbitrary-dimensional continuous variable x, how can I use Mathematica to create a function that will return a set of n random samples of x with distribution p?

An answer that assumes p[x_] and all of its derivatives are smooth and continuous would be helpful, but an answer that does not assume that would be even better.

• Depends. Does RandomVariate[] work with a ProbabilityDistribution[] built from your PDF? You can always do rejection sampling otherwise. Apr 13, 2016 at 1:40
• @J.M. That worked. Thank you. (This is where it would be nice if the MMa documentation had more practical examples of using functions in conjunction.) Apr 13, 2016 at 2:15
• Consider answering your own question if you did figure things out. Apr 13, 2016 at 4:13

Thanks for the solution, J.M.

(* create an example pdf *)
f[x_] := Exp[-x^4 + x^2];
normf = NIntegrate[f[x], {x, -Infinity, Infinity}];
p[x_] = f[x]/normf;
Plot[p[x], {x, -2, 2}]

(* How to generate samples from p[x] *)
pd = ProbabilityDistribution[p[x], {x, -Infinity, Infinity}];
d = RandomVariate[pd, 100000];
Histogram[d, 100]


• Method -> Normalize can be a useful setting at times. Apr 13, 2016 at 8:53