This seems to be a really strange issue:
This is my code:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { @autoreleasepool { srand((unsigned int)time(NULL)); int newRandomNumber = 0; newRandomNumber = rand() % 7; NSLog(@"%d", rand() % 7); //This prints out what I expected NSLog(@"newRandomNumber = %d", newRandomNumber); // This always prints out 0! } return 0; }
If I replace that one line that says
newRandomNumber = rand() % 7
with
newRandomNumber = rand() % 8
everything works perfectly. Why is that the case?
rand() in C/C++ gives a number between 0 and RAND_MAX, which is guaranteed to be at least 32767.
The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
The value of this macro is an integer constant representing the largest value the rand function can return. In the GNU C Library, it is 2147483647 , which is the largest signed integer representable in 32 bits. In other libraries, it may be as low as 32767 .
rand() / RAND_MAX is equal to 0. For example 2 / 5 == 0 for integer numbers. If you want floating point division you have to explicitly cast at least one of the sides of /. Also, C++11 provides its own random library.
Well, this
int seed; for(seed = 1; seed < 10; seed++) { srand(seed); printf("%4d %16d\n", seed, rand()); }
prints
1 16807 2 33614 3 50421 4 67228 5 84035 6 100842 7 117649 8 134456 9 151263
which makes me think that rand() = seed * 16807
Wikipedia article Linear congruential generator confirms that CarbonLib indeed uses Xn+1 = Xn * 16807 to generate random numbers.
It seems unlikely but running some tests, after an srand the first rand seems always to be divisible by 7, at least in an int sized variable.
On several runs I got 1303562743, 2119476443, and 2120232758, all of which mod 7 to 0.
The second rand()
works, because it is the second rand()
. Throw a rand()
before your first rand()
... or better yet, use a better random number generator random
or arc4rand
if available.
Also see Stack Overflow question Why is (rand() % anything) always 0 in C++?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With