iphone--随机数思考: rand()与arc4random()比较
来源:互联网 发布:mysql 时间加1秒 编辑:程序博客网 时间:2024/06/06 06:44
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);
原文出处: (注: blogspot在国内无法访问)
http://iphonedevelopment.blogspot.com/2008/10/random-thoughts-rand-vs-arc4random.html
- iphone--随机数思考: rand()与arc4random()比较
- iphone--随机数思考: rand()与arc4random()比较
- 随机数思考: rand()与arc4random()比较
- ios--随机数rand、random、arc4random
- rand() 与 arc4random()的选用
- iPhone开发随想:rand()还是arc4random()
- iPhone开发随想:rand()还是arc4random()
- iPhone开发随想:rand()还是arc4random()
- iPhone开发随想:rand()还是arc4random()
- 随机函数之 rand() 与 arc4random() 对比
- 随机数(rand与srand)
- rand()还是arc4random()
- objective-c 中随机数的用法 (rand()、arc4random() 、random()、CCRANDOM_0_1() )
- iOS 中生成随机数的4种方法(rand、random、arc4random、arc4random_uniform)
- srand与rand随机数生成
- comparison between rand() and arc4random()
- 产生随机数:arc4random()函数
- 随机数,and()、random()、arc4random()
- 导出到word
- Active MQ C++实现通讯
- log4j按级别分类输出日志到相对路径日志文件
- 使用Boost.Asio编写通信程序
- imagick安装
- iphone--随机数思考: rand()与arc4random()比较
- Objective-C 2.0的运行时编程
- 多线程程序常见Bug剖析(上)
- 如何在wince下 建立文件夹
- 深入理解.Net中的内存释放,以及有关的注意事项
- 发送短信基本程序
- 第一个BeagleBoard上的QNX程序
- 系统编程
- str.replaceAll()和str.replace()的区别不可小视