2
$\begingroup$

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.

$\endgroup$
3
  • 3
    $\begingroup$ Depends. Does RandomVariate[] work with a ProbabilityDistribution[] built from your PDF? You can always do rejection sampling otherwise. $\endgroup$ Apr 13, 2016 at 1:40
  • $\begingroup$ @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.) $\endgroup$ Apr 13, 2016 at 2:15
  • $\begingroup$ Consider answering your own question if you did figure things out. $\endgroup$ Apr 13, 2016 at 4:13

1 Answer 1

4
$\begingroup$

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]

i1

i2

$\endgroup$
1
  • 2
    $\begingroup$ Method -> Normalize can be a useful setting at times. $\endgroup$ Apr 13, 2016 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.