Is rand() not that random??
Is rand() not that random??
- Subject: Is rand() not that random??
- From: Alexandre Aybes <email@hidden>
- Date: Mon, 10 Dec 2001 04:20:02 +0100
Hi there I am having some difficulties getting random numbers...
I know this question is not really a cocoa-dev question, but I
thought someone here might have a good answer to my problem :))
And I am using cocoa for my app... uhhh... anyay...
I want to compute random numbers from 1 to X (X being an
arbitrary value computed at runtime). This sounds like a very
simple problem and I thought it would take 2 seconds to
implement, and I took the quick and durty path by just computing
it so: 'rand() % X' I thought that it would work... but it
doesn't seem to...
When I take the whole number returned by rand I don't seem to be
able to make up a pattern but if I take its modulus 4, it just
returns 2 3 0 1 2 3 0 1... (only starting with a random number).
Below the code and the output in this example X is 4 but it
works with other numbers as well... :)
Code:
{
time_t theTime = 0;
srand(time(&theTime));
NSLog(@"Random value: %i", rand() % 4);
NSLog(@"Random value: %i", rand() % 4);
NSLog(@"Random value: %i", rand() % 4);
NSLog(@"Random value: %i", rand() % 4);
NSLog(@"Random value: %i", rand() % 4);
NSLog(@"Random value: %i", rand() % 4);
NSLog(@"Random value: %i", rand());
NSLog(@"Random value: %i", rand());
NSLog(@"Random value: %i", rand());
NSLog(@"Random value: %i", rand());
NSLog(@"Random value: %i", rand());
NSLog(@"Random value: %i", rand());
}
Output:
2001-12-10 03:41:04.247 BomberMac[5126] Random value: 1
2001-12-10 03:41:04.285 BomberMac[5126] Random value: 2
2001-12-10 03:41:04.309 BomberMac[5126] Random value: 3
2001-12-10 03:41:04.332 BomberMac[5126] Random value: 0
2001-12-10 03:41:04.348 BomberMac[5126] Random value: 1
2001-12-10 03:41:04.373 BomberMac[5126] Random value: 2
2001-12-10 03:41:04.396 BomberMac[5126] Random value: 2037401275
2001-12-10 03:41:04.421 BomberMac[5126] Random value: 436029400
2001-12-10 03:41:04.437 BomberMac[5126] Random value: 634099505
2001-12-10 03:41:04.463 BomberMac[5126] Random value: 10911254
2001-12-10 03:41:04.481 BomberMac[5126] Random value: 475173783
2001-12-10 03:41:04.498 BomberMac[5126] Random value: 904595844
I'm aware of the implementation problems that a pseudo random
generator brings, but still this doesn't seem to me as a
particularly clever way of doing it... :/ Or maybe I am totally
wrong...
If one of you has a better way of getting a random number
between 0 and X... let me know.
Thanks,
Alex.