14
$\begingroup$

Please consider the following:

From a fresh Mathematica kernel, RandomVariate is more efficient for NormalDistribution but RandomReal is for uniformly distributed noise.

RandomReal[NormalDistribution[0, 1], 100]; // Timing

{0.00535, Null}

RandomVariate[NormalDistribution[0, 1], 100]; // Timing

{0.000069, Null}

RandomReal[{0, 1}, 100]; // Timing

{0.00004, Null}

RandomVariate[UniformDistribution[], 100]; // Timing

{0.005236, Null}

But if I re-evaluate, I get Timing results that are much more similar:

RandomReal[NormalDistribution[0, 1], 100]; // Timing

{0.000051, Null}

RandomVariate[NormalDistribution[0, 1], 100]; // Timing

{0.000052, Null}

RandomReal[{0, 1}, 100]; // Timing

{0.00003, Null}

RandomVariate[UniformDistribution[], 100]; // Timing

{0.000058, Null}

Does caching the distribution definition really matter that much?

Obviously RandomVariate has the advantage that it can generate data from mixed (not only fully continuous or fully discrete) distributions. So it is more general. But if one is generating random numbers from standard distributions like the normal or the Poisson, is there any advantage – performance or otherwise – to using RandomVariate instead of RandomReal or RandomInteger?

$\endgroup$
  • 5
    $\begingroup$ I didn't even know that RandomReal worked for distributions $\endgroup$ – Rojo Mar 4 '12 at 3:55
  • 2
    $\begingroup$ @Rojo It doesn't seem to be in the main documentation for RandomReal in v8, but can be verified to work with Histogram@RandomReal[NormalDistribution[0, 1], 1000]. It is the way to do it in version 7, and I hadn't adapted to RandomVariate yet. $\endgroup$ – Verbeia Mar 4 '12 at 4:02
  • $\begingroup$ Interesting question $\endgroup$ – Rojo Mar 4 '12 at 5:26
18
$\begingroup$

In general you should use RandomVariate for distributions and RandomReal for uniforms. Often RandomVariate calls RandomReal or RandomInteger under the hood but it varies on a distribution by distribution basis. After loading any necessary symbols, on evaluation, any timing differences should be negligible.

RandomVariate is intended to give the flexibility to not have to think of whether the distribution is continuous or discrete (or mixed), it has also been optimized for each distribution in the system. One should always be able to use RandomInteger or RandomReal if the type is known ahead of time (and is not mixed or fuzzy in some way e.g. EmpiricalDistribution) but again, most of the overhead is in initializing the generator so if you are generating a large number of random numbers you shouldn't notice a big difference in timings after evaluating both RandomVariate and RandomReal/RandomInteger.

$\endgroup$

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.