srandom(time(NULL));
But... rand() is really not a very good PRNG. random() is a little better, but still less then ideal. Fortunately, these are not the only ones available on the iPhone. Personally, I like arc4random() because it's a decent pseudo-random algorithm and has twice the range or rand().
On the iPhone, RAND_MAX is 0x7fffffff (2147483647), while arc4random() will return a maximum value of 0x100000000 (4294967296), giving much more precision. You also don't need to seed arc4random(), as the first call to it automatically seeds it.
To get an integer value from arc4random() that goes from 0 to x-1, you would do this:
int value = arc4random() % x;
To get an integer in the range 1 to x, just add 1:
int value = (arc4random() % x) + 1;
The parenthesis aren't really necessary based on order of operation rules, but I'm anal about parens.
Finally, if you need to generate a floating point number, define this in your project:
#define ARC4RANDOM_MAX 0x100000000
Then, you can use arc4random() to get a floating point value (at double the precision of using rand()), between 0 and 100, like so:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);
No comments:
Post a Comment