Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number bigger than 100,000

I'm writing in C/C++ and I want to create a lot of random numbers which are bigger than 100,000. How I would do that? With rand();

like image 974
BlackM Avatar asked Nov 21 '12 23:11

BlackM


4 Answers

You wouldn't do that with rand, but with a proper random number generator which comes with newer C++, see e.g. cppreference.com.

const int min = 100000;
const int max = 1000000;
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(min,max);
int random_int = distribution(generator);  // generate random int flat in [min, max]

Don't forget to properly seed your generator.

Above I imply that rand is not a "proper" pseudo-RNG since it typically comes with a number of shortcomings. In the best case, it lacks abstraction so picking from a different distribution becomes hard and error-prone (search the web for e.g. "random range modulus"). Also replacing the underlying engine used to generate the random numbers is AFAIK impossible by design. In less optimal cases rand as a pseudo-RNG doesn't provide long enough sequence lengths for many/most use cases. With TR1/C++11 generating high-quality random numbers is easy enough to always use the proper solution, so that one doesn't need to first worry about the quality of the used pseudo-RNG when obscure bugs show up. Microsoft's STL gave a presentation giving a nice summary talk on the topic at GoingNative2013.

like image 96
Benjamin Bannier Avatar answered Oct 17 '22 15:10

Benjamin Bannier


// Initialize rand()'s sequence. A typical seed value is the return value of time()
srand(someSeedValue);

//...

long range = 150000; // 100000 + range is the maximum value you allow
long number = 100000 + (rand() * range) / RAND_MAX;

You may need to use something larger than a long int for range and number if (100000 + range) will exceed its max value.

like image 27
Jason Avatar answered Oct 17 '22 14:10

Jason


In general you can use a random number generator that goes between 0 and 1, and get any range you want by doing the following transformation:

x' = r x + b

So if you want random numbers between, say, 100,000 and 300,000, and x is your random number between 0 and 1, then you'd set r to be 200,000 and b to be 100,000 and x' will be within the range you want.

like image 31
John Avatar answered Oct 17 '22 14:10

John


If you don't have access to the C++ builtins yet, Boost has a bunch of real randomizers in Boost.Random, including specific solutions for your apparent problem space.

I'd echo the comments that clarifying edits in your question would improve the accuracy of answers eg. "I need uniformly-distributed integers from 100,001 through 1,000,000".

like image 1
Steve Townsend Avatar answered Oct 17 '22 13:10

Steve Townsend