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()
FYI - It's actually RAND_MAX, rather than MAX_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.
the answer is
rand() * MAX_RAND + rand()
I think you want something like this:
rand() << lg2((long)RAND_MAX+1) + rand()
Which simplifies to this:
(long)rand()<<32 | (short)rand()
Huh... What a nice way to generate a high number that was never intended to be generated by the function. I like it! :p
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.
Originally Posted by King Mir
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:
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)