Rand_Max*(max-min)+min << what is that?

c++, c++11, random, srand, stl

Solution

`static_cast<double>(ran())/RAND_MAX*(max-min)+min);`

I'm assuming you mistyped `rand()`, which returns a pseudorandom integer from 0 to RAND_MAX. Let's rewrite that in a way that clarifies the precedence a bit:

`(T) ( (((double) rand() / RAND_MAX) * (max-min) ) + min`

So what it does is:

- `rand()`: take a random integer between 0 and RAND_MAX

- `(double) / RAND_MAX`: divide as double by RAND_MAX, yielding a uniformly distributed double between 0 and 1:

- `* (max-min)`: multiply by the range `(max-min)`, yielding a double from 0 to (max-min)

- `+min`: add the minimum to yield a random double between min and max

- `static_cast<T>`: cast it back to the original type

The result is a uniformly distributed random number of type T between `min` and `max`.

Problem

``` generate(vec.begin(), vec.end(), [=](){return static_cast<T>(static_cast<double>(ran()) /RAND_MAX*(max-min)+min); }); ``` Problem: RAND_MAX*(max-min)+min); Ok, so I know the algorithms, lambda expressions, and, capture clause in this thing. My question is quite ridiculous to all of that. What is the bolded text above mean. I mean, I know its part of the random value generation process. But don't know exactly what the hell is going on. So can someone pls break down that tinny tiny little code.

Original source