I need a function which would generate a random integer in a given range (including boundary values). I don't have unreasonable quality/randomness requirements; I have four requirements:
- I need it to be fast. My project needs to generate millions (or sometimes even tens of millions) of random numbers and my current generator function has proven to be a bottleneck.
- I need it to be reasonably uniform (use of rand() is perfectly fine).
- the minimum-maximum ranges can be anything from to .
- it has to be seedable.
I currently have the following C++ code:
output = min + (rand() * (int)(max - min) / RAND_MAX)
The problem is that it is not really uniform - max is returned only when rand() = RAND_MAX (for Visual C++ it is 1/32727). This is a major issue for small ranges like , where the last value is almost never returned.
So I grabbed pen and paper and came up with following formula (which builds on the (int)(n + 0.5) integer rounding trick):
( (max - min) * rand() + (RAND_MAX / (2 * (max - min))) ) / RAND_MAX
But it still doesn't give me a uniform distribution. Repeated runs with 10000 samples give me ratio of 37:50:13 for values values -1, 0. 1.
Is there a better formula? (Or even whole pseudo-random number generator function?)
0 answers
Hot tools Tags
Hot Questions
Popular tool
vc9-vc14 (32+64 bit) runtime library collection (link below)
Download the collection of runtime libraries required for phpStudy installation
VC9 32-bit
VC9 32-bit phpstudy integrated installation environment runtime library
PHP programmer toolbox full version
Programmer Toolbox v1.0 PHP Integrated Environment
VC11 32-bit
VC11 32-bit phpstudy integrated installation environment runtime library
SublimeText3 Chinese version
Chinese version, very easy to use
Hot Topics
20522
7
13634
4






