Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Random number from 1 to a very large number (e.g. 25 million)

How would you make a function that generates a random number from 1 to 25 million?

I've thought about using rand() but am I right in thinking that the maximum number, RAND_MAX is = 32000 (there about)?

Is there a way around this, a way that doesn't reduce the probability of picking very low numbers and doesn't increase the probability of picking high / medium numbers?

Edit: @Jamey D 's method worked perfectly independent of Qt.

like image 694
AlarmingMonkey Avatar asked Dec 10 '15 19:12

AlarmingMonkey


People also ask

What is the most random number ever?

We are told that MIPS chip designer Mark Johnson, who claims it is the World's most common random number, is responsible for scribbling this number onto the mask. A number of visitors have responded to us about the concept of 37 being the most random number.

What is a random number in C?

Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.

How do you generate a random number in a range in C++?

How to Generate Random Numbers in C++ Within a Range. Similar to 1 and 10, you can generate random numbers within any range using the modulus operator. For instance, to generate numbers between 1 and 100, you can write int random = 1+ (rand() % 100).


2 Answers

You could (should) use the new C++11 std::uniform_real_distribution

#include <random>

std::random_device rd;
std::mt19937 gen(rd());

std::uniform_real_distribution<> distribution(1, 25000000);

//generating a random integer:
double random = distribution(gen);
like image 161
Hatted Rooster Avatar answered Oct 04 '22 08:10

Hatted Rooster


Have a look at ran3

http://www.codeforge.com/read/33054/ran3.cpp__html

You should be able to get what you want from it.

Ran3 is (atleast when I was still doing computational modelling) faster than rand() with a more uniform distribution, though that was several years ago. It returns a random integer value.

For example, getting the source code from the link above:

int main() {
   srand(time(null));

   int randomNumber = ran3(rand()) % 25000000;
   int nextRandomNumber = ran3(randomNumber);
}
like image 22
Ajwhiteway Avatar answered Oct 04 '22 08:10

Ajwhiteway