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:

the answer is

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.

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

psyadam

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