# Max_rand

• 10-25-2007
Max_rand
Hey guys, I'll be googling and such and will probably find the answer before someone can reply, but in case this problem is trickier than it seems, here's the problem I am having.

Basically, I never needed to have a random number that was bigger than 0x7fff (a little over 32000 in decimal) until now. But I want to be able to generate a random number that is say, a number between 0 and 1000000. How can I do this, and still have the number be truly random, i.e. each number between 0 and 1000000 is just as likely?

edit: I think I just figured it out just by thinking about it

the answer is rand() * MAX_RAND + rand()
• 10-25-2007
DougDbug
FYI - It's actually RAND_MAX, rather than MAX_RAND. ;)

Quote:

Code:

` rand() * MAX_RAND + rand()`

Hmmmm.... I don't think that will give you an even-uniform distribution.. I think that's going to favor big numbers, but I'd better leave that one for the experts.
• 10-25-2007
King Mir
I think you want something like this:
rand() << lg2((long)RAND_MAX+1) + rand()
Which simplifies to this:
(long)rand()<<32 | (short)rand()
• 10-25-2007
Elysia
Huh... What a nice way to generate a high number that was never intended to be generated by the function. I like it! :p
• 10-25-2007
iMalc
Quote:

Originally Posted by King Mir
I think you want something like this:
rand() << lg2((long)RAND_MAX+1) + rand()
Which simplifies to this:
(long)rand()<<32 | (short)rand()

That shift can't be supposed to be by 32 or else he would already be able to generate big enough random numbers. You must mean 16.
• 10-26-2007
King Mir
Er, yeah.
• 10-27-2007
I wrote some code to test the uniformity of the distribution of my random number generator and it appears to be uniform. My first idea, btw, was to use rand() * rand() + rand(), which does not give you a uniform distrubution :)

It gives you a distribution like this:

0: 329470
1: 192222
2: 139096
3: 105084
4: 80234
5: 59911
6: 43583
7: 28865
8: 16319
9: 5216
Press any key to continue

where the numbers 0-9 represent 10 equal ranges for the LargeRand() function

(edit: i.e. if SUPER_RAND_MAX was 1,000,000, 0 would represent the number of numbers in the range 0 to 100,000, 1 would represent the number of numbers in the range 100,000 to 200,000 etc)