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

不想你离开。 提交于 2019-12-28 23:48:05

问题


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.


回答1:


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);



回答2:


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);
}


来源:https://stackoverflow.com/questions/34209690/c-random-number-from-1-to-a-very-large-number-e-g-25-million

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!