2
$\begingroup$

Consider the two tests:

Timing[Do[RandomVariate[NormalDistribution[0.5, 0.3]], {200}]]  

{0.001188, Null}

MyNormalDistribution[mu_,sig_] = ProbabilityDistribution[1/(Sqrt[2 \[Pi]]sig)
             Exp[-(x - mu)^2/(2 sig^2))], {x, -\[Infinity], \[Infinity]}];
Timing[Do[RandomVariate[MyNormalDistribution[0.5, 0.3]], {200}]]

{3.375444, Null}

So it seems that the built in normal distribution is much faster (~3000 times faster!) then the custom one. My question is how is this optimization done and whether it can be implemented for custom distributions as well?

$\endgroup$
  • 1
    $\begingroup$ Related questions: (1124), (20067), (56180), (75303) $\endgroup$ – dr.blochwave Apr 24 '15 at 14:56
  • $\begingroup$ In particular question #1124 $\endgroup$ – dr.blochwave Apr 24 '15 at 14:58
  • $\begingroup$ The LHS of your definition should read MyNormalDistribution[mu_, sig_] Without the patterns, MyNormalDistribution[0.5, 0.3] is undefined. Even after this correction, RandomVariate[MyNormalDistribution[0.5, 0.3]] does not return a value. RandomVariate only works with the built-in distributions. You would need to define an upvalue for MyNormalDistribution to have RandomVariate work. $\endgroup$ – Bob Hanlon Apr 24 '15 at 16:16
  • $\begingroup$ @BobHanlon, You are right about the missing underscores, thanks. This was a typo. However, RandomVariate does work with custom distributions (at least in v10). Feel free to try it yourself.... $\endgroup$ – JeffDror Apr 24 '15 at 16:45
  • 1
    $\begingroup$ Do you really require them one at a time? Is the distribution changing between calls (only real reason I can think of that would need singlets)? Otherwise, produce them in bulk, will be orders of magnitude faster. $\endgroup$ – ciao Apr 13 '16 at 5:29

Your Answer

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

Browse other questions tagged or ask your own question.