Thread: Random numbers

1. Random numbers

Hey all,

Im trying to produce random numbers in the range of 1 to 50,000 using the rand() function.

just a little curiouse as to how this function works.

Ive been fiddling with it and i havent learnt much. Im guessing the seed you enter should influence the numbers generated, but ive been entering in new seeds to find that the numbers generated are exactly the same. This could have something to do with the complexity of my seeds however..

i tried numbrs like 7, 50.. then randomly mashing the number pad. but it didnt work.

if i don't use a seed but a formulae such as:

i = 1+(int) (10.0 * rand()/(RAND_MAX + 1.0))

it will generate what seems to be random but each time it is called.. each time the program is run the pattern is exactly the same.

I tried entering a seed into the rand function here but it didnt seems to make any difference.

Also one last thing. This formula is supposed to generate numbers betweek 1 and 10. but it doesnt.

thanks,

2. This should work for you.
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ( void )
{
int i = 0;
srand ( time ( NULL ) );
while ( i < 50 )
printf ( "%u\n", 1 + rand() % 50000 ), i++;
return EXIT_SUCCESS;
}```
-Prelude

3. thanks

hey thanks,

I didnt know about the srand function.

now that i know about that it works fine.

If I do it the way your suggest however it will use low ordered bits. I need to use high ordered.

Thanks all the same.

cheers,

4. Additionally, you could always READ THE FAQ.

Quzah.

5. This makes your "random" numbers more random:
Code:
`rand()*rand()*rand()%MAX;`
klausi

6. Hi,
I didnt understand this statement

printf ( "%u\n", 1 + rand() % 50000 ), i++;

Could u please explain it in detail to me?

7. Hi,
Be aware that different compilers have different values for RAND_MAX.

Thus the formula

x = rand() % 50000 + 1

may not give a vaule higher than 32,768.

Popular pages Recent additions