Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient is it to make a temporary uniform random distribution each time round a loop?

For example:

for (...)
{
    ... std::uniform_real_distribution<float>(min, max)(rng) ...
}

Intuitively it seems to me that the constructor can't need to do much besides store the two values, and there shouldn't be any state in the uniform_*_distribution instance. I haven't profiled it myself (I'm not at that kind of stage in the project yet), but I felt this question belonged out there :)

I am aware that this would be a bad idea for some distribution types - for example, std::normal_distribution might generate its numbers in pairs, and the second number would be wasted each time.

I feel what I have is more readable than just accessing rng() and doing the maths myself, but I'd be interested if there are any other ways to write this more straightforwardly.

like image 856
entheh Avatar asked Jan 21 '16 21:01

entheh


People also ask

How do you generate uniformly distributed random numbers?

The Uniform Random Number block generates uniformly distributed random numbers over an interval that you specify. To generate normally distributed random numbers, use the Random Number block. Both blocks use the Normal (Gaussian) random number generator ( 'v4' : legacy MATLAB® 4.0 generator of the rng function).

What does uniformly random mean?

1 The Uniform Random Variable. A random variable is said to be uniformly distributed over the interval if its probability density function is given by. Note that the preceding is a density function since and. Since only when , it follows that must assume a value in .


1 Answers

std::uniform_real_distribution's objects are lightweight, so it's not a problem to construct them each time inside the loop.

Sometimes, the hidden internal state of distribution is important, but not in this case. reset() function is doing nothing in all popular STL implementations:

void
reset() { }

For example, it's not true for std::normal_distribution:

void
reset()
{ _M_saved_available = false; }
like image 156
SashaMN Avatar answered Nov 14 '22 22:11

SashaMN