Reputation: 368
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.
Upvotes: 2
Views: 5373
Reputation: 4623
the ran() function returns a random value between min and max ?
but sometimes we need a random value between A and B (min and max). So we can adjust the result for it.
a is double, so we use a static_cast!
a = rand() ; 0 <= a <= RAND_MAX
a = a/RAND_MAX ; 0 <= a <= 1
a = B * a ; 0 <= a <= B
a = min +a ; 0+min <= a <= B+min
to produce min <= a <= max,
B+min = max
B = max-min
in other hands
a = rand()/RAND_MAX*(max-min) + min
is a random number between min and max.
Upvotes: 0
Reputation: 3709
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 maxstatic_cast<T>
: cast it back to the original typeThe result is a uniformly distributed random number of type T between min
and max
.
Upvotes: 8
Reputation: 9140
You'll need to look at the entire expression: static_cast<double>(rand())
/RAND_MAX*(max-min)+min)
. Which with explicit grouping looks like: (static_cast<double>(rand())
/RAND_MAX)*(max-min)+min)
.
The first group returns a random value between 0 & 1 since rand()
returns a value in the range 0 to RAND_MAX. The second group translates the 0 to 1 range to a min
to max
range.
Upvotes: 2
Reputation: 724
The expression static_cast<double>rand()/RAND_MAX
creates a number between 0.0 and 1.0
When you multiply it by (max-min)
, you change the range, and when you add to min
you shift the range. So, after that expression you have a random number (double) that ranges from min
to max
.
Upvotes: 3
Reputation: 5687
It's a random function limited on the downside by min (because the rand piece could return zero) and limited to max because even if it returned 100% of max-min, and added to min, you'd be at max
Upvotes: 2