随机数思考: rand()与arc4random()比较

来源:互联网 发布:直播软件你懂得 编辑:程序博客网 时间:2024/06/06 16:26

Random Thoughts: rand() vs. arc4random()

There are several built-in randomizers on the iPhone, and most people's first thought is to use rand() after seeding it by calling

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

原文出处:

http://iphonedevelopment.blogspot.com/2008/10/random-thoughts-rand-vs-arc4random.html

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wave_1102/archive/2009/11/09/4789167.aspx

原创粉丝点击