Hello,

I need to random generate some values in c++. I know that I can use rand() but I need to generate values with the following condition: the generated values must be equal to 2^n (0, 2, 4, 8, ...). Is that possible?

Kind regards,

M.

miskeen
0
Junior Poster in Training

Hello,

I need to random generate some values in c++. I know that I can use rand() but I need to generate values with the following condition: the generated values must be equal to 2^n (0, 2, 4, 8, ...). Is that possible?

Kind regards,

M.

Jump to PostTo get a random int between 0 and 31 (inclusive) using rand(), prefer something like

`int( 32.0 * ( rand() / (RAND_MAX+1.0) ) ) ;`

Or else, you would be assuming that the least significant 5 bits of the pseudo random number generated by rand() are also randomly distributed.

L7Sqr
227
Practically a Master Poster

`std::random_shuffle`

that vector. At that point you could just iterate over the shuffled vector to get random values.

mike_2000_17
2,669
21st Century Viking
Team Colleague
Featured Poster

First: seed you random number generator once with `srand(time(NULL))`

.

Then, get a value between 0 and 31 using the modulus operator on the result of rand(), as so `rand() % 32`

. That gives you "n".

Finally, use the bitshift operator to raise to the power of "n". As so `1 << n`

.

And, that's it. Enjoy!

vijayan121
1,152
Posting Virtuoso

`int( 32.0 * ( rand() / (RAND_MAX+1.0) ) ) ;`

Or else, you would be assuming that the least significant 5 bits of the pseudo random number generated by rand() are also randomly distributed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.