C++ Random number from 1 to a very large number (e

2019-01-19 18:01发布

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.

2条回答
Luminary・发光体
2楼-- · 2019-01-19 18:34

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);
}
查看更多
Viruses.
3楼-- · 2019-01-19 18:35

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);
查看更多
登录 后发表回答