Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I scale down numbers from rand()?

The following code outputs a random number each second:

int main () {     srand(time(NULL)); // Seeds number generator with execution time.      while (true)     {         int rawRand = rand();          std::cout << rawRand << std::endl;          sleep(1);     } } 

How might I size these numbers down so they're always in the range of 0-100?

like image 403
Maxpm Avatar asked Nov 16 '10 15:11

Maxpm


People also ask

How do you scale a Rand?

For example, rand() % 6 will produce a random number between 0 and 5. Scaling a random number as an integer value between 1 and N may be accomplished by using the expression rand() % N + 1 or 1 + rand() % N. For example, 1 + rand() % 6 will produce a random number between 1 and 6.

Why is rand () giving me the same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

What does RAND () Rand_max do?

Expands to an integer constant expression equal to the maximum value returned by the function std::rand.

What is range of rand ()?

The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.


1 Answers

If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>.

#include <random>  std::random_device rseed; std::mt19937 rgen(rseed()); // mersenne_twister std::uniform_int_distribution<int> idist(0,100); // [0,100]  std::cout << idist(rgen) << std::endl; 
like image 181
Blastfurnace Avatar answered Sep 20 '22 16:09

Blastfurnace