Hmm? For the case rand() is 15, then r = 1.0f. The result is begin + (r * range), where range is 5. So the result would be 5 in this case, not 6. Am I wrong?
With the code involving the conversion to and from floating point you get:
- 0 if rand() was 0, 1, or 2
- 1 if rand() was 3, or 4
- 2 if rand() was 5, 6, or 7
- 3 if rand() was 8 or 9
- 4 if rand() was 10, 11, or 12
- 5 if rand() was 13 or 14,
- 6 if rand() was 15 (bug!!!)
In fact, this is the output I get:
- 0 if rand() is 0, 1 or 2
- 1 if rand() is 3, 4 or 5
- 2 if rand() is 6, 7 or 8
- 3 if rand() is 9, 10 or 11
- 4 if rand() is 12, 13 or 14
- 5 if rand() is 15
Ok, that is indeed better.
With the rejection method above you get...
I was thinking of the wrong problem, I believe a corrected version of the function I provided could be used to extend the range of values above RAND_MAX (without calling rand() multiple times). E.g. We want a potentially very large float or double, but we're happy to accept a sample of RAND_MAX values in that range (as opposed to mandating that any value in the range could appear).
For applications requiring cryptographic random numbers, sure.
Oh and one final note, on Windows, the ultimate random number generator is CryptGenRandom. :-)