随机数思考: 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
- iphone--随机数思考: rand()与arc4random()比较
- 随机数思考: rand()与arc4random()比较
- iphone--随机数思考: rand()与arc4random()比较
- ios--随机数rand、random、arc4random
- 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()
- 使用 arc4random获取随机数
- rand()随机数
- Rand 随机数
- 随机数Rand()
- 如何在安装或运行时检查S60平台版本
- 通过dll来引用webservice的方法(.net)
- 用Ant和JUnit构建自动化测试
- Android.mk文件用法与基础
- Monitoring WebLogic using JMX
- 随机数思考: rand()与arc4random()比较
- 懒加载异常org.hibernate.LazyInitializationException: could not initialize proxy - no
- CLR Via C#读书笔记——垃圾收集相关知识点【2011-01-20】
- volatile 变量使用指南
- 用 JProfiler4 调优 Weblogic 和 Tomcat 的视频
- xp下让iis支持asp.net (转载)
- 颜色16进制代码表-显示和16进制数值对比显示方便查找
- IE8 一窗多浏览
- 总结一个技巧 通过图片查找资料