ios取两个数之间的随机小数_(转)ios随即数

(转)ios随即数

今 天在iPhone开发过程中,遇到一个需要生成随机数的问题。很快rand()和arc4random()都进入了考虑范围,但选择的时候感觉有点为难。 之前的时候可能没有思索就随便挑一个用了,不过这次良心发现不能太随便了。rand() 和arc4random()到底应该如何取舍呢?调查了下,发现下文很好地解答了这个问题。

在iPhone中有几个内嵌的随机数发生器,很多人的第一反应可能就是在调用如下函数后使用rand():

srandom(time(NULL));

但是……,rand()实际并不是一个真正的伪随机数发生器,random()会相对好点,但也不算理想。幸运的是iPhone上还有其他的选择。个人来说我首选arc4random() ,原因就是它是一个真正的伪随机算法,而且范围是rand()的两倍。

在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的最大值则是

0x100000000

(4294967296),从而有更好的精度。此外,使用arc4random()还不需要生成随机种子,因为第一次调用的时候就会自动生成。

通过arc4random() 获取0到x-1之间的整数的代码如下:

intvalue=arc4random() % x;

获取1到x之间的整数的代码如下:

intvalue= (arc4random() % x) + 1;

其中,根据预算优先级括号实际是不需要的,不过我还是对括号格外小心。

最后如果想生成一个浮点数,可以在项目中定义如下宏:

#define ARC4RANDOM_MAX      0x100000000

然后就可以使用arc4random() 来获取0到100之间浮点数了(精度是rand()的两倍),代码如下:

doubleval=floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值