1
$\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
    $\begingroup$ Depends. Does RandomVariate[] work with a ProbabilityDistribution[] built from your PDF? You can always do rejection sampling otherwise. $\endgroup$ – J. M. will be back soon Apr 13 '16 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$ – Jerry Guern Apr 13 '16 at 2:15
  • $\begingroup$ Consider answering your own question if you did figure things out. $\endgroup$ – J. M. will be back soon Apr 13 '16 at 4:13
3
$\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$
  • 2
    $\begingroup$ Method -> Normalize can be a useful setting at times. $\endgroup$ – J. M. will be back soon Apr 13 '16 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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