在Objective-C中生成随机数
时间:2020-03-06 15:00:34 来源:igfitidea点击:
我主要是Java主管,并且我想要一种生成0到74之间的伪随机数的方法。在Java中,我将使用以下方法:
Random.nextInt(74)
我对讨论种子或者真正的随机性不感兴趣,而对我们如何在Objective-C中完成相同的任务不感兴趣。我曾搜寻过Google,但似乎有很多不同且相互冲突的信息。
解决方案
和C一样,你会做
#include <time.h> #include <stdlib.h> ... srand(time(NULL)); int r = rand() % 74;
(假设意思是包括0但不包括74,这是Java示例所做的事情)
编辑:随意将rand()替换成random()或者arc4random()即可(就像其他人指出的那样,很烂)。
根据rand(3)的手册页,rand(3)函数已被random(3)淘汰。这是由于rand()的低12位经过循环模式这一事实。要获得随机数,只需通过使用无符号种子调用srandom()来为生成器添加种子,然后调用random()即可。因此,上面的代码等效于
#import <stdlib.h> #import <time.h> srandom(time(NULL)); random() % 74;
我们只需要在程序中调用srandom()一次,除非我们想更改种子。尽管我们说过我们不想讨论真正的随机值,但是rand()是一个非常糟糕的随机数生成器,并且random()仍然会遭受模偏差,因为它将生成介于0和RAND_MAX之间的数字。因此,例如如果RAND_MAX为3,并且我们想要一个0到2之间的随机数,那么获得0的可能性是1或者2的两倍。
我们应该使用arc4random_uniform()函数。它使用高级算法进行求和。我们甚至不需要设置种子。
#include <stdlib.h> // ... // ... int r = arc4random_uniform(74);
arc4random手册页:
NAME arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <stdlib.h> u_int32_t arc4random(void); void arc4random_stir(void); void arc4random_addrandom(unsigned char *dat, int datlen); DESCRIPTION The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo- random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3). The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via arc4random_addrandom(). There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically initializes itself. EXAMPLES The following produces a drop-in replacement for the traditional rand() and random() functions using arc4random(): #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
我编写了自己的随机数实用程序类,以便可以使用类似于Java中的Math.random()的函数。它只有两个功能,并且全部用C编写。
头文件:
//Random.h void initRandomSeed(long firstSeed); float nextRandomFloat();
实施文件:
//Random.m static unsigned long seed; void initRandomSeed(long firstSeed) { seed = firstSeed; } float nextRandomFloat() { return (((seed= 1664525*seed + 1013904223)>>16) / (float)0x10000); }
这是生成伪随机数的一种非常经典的方法。在我的应用程序委托中,我致电:
#import "Random.h" - (void)applicationDidFinishLaunching:(UIApplication *)application { initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] ); //Do other initialization junk. }
然后,我只是说:
float myRandomNumber = nextRandomFloat() * 74;
请注意,此方法返回一个介于0.0f(含)和1.0f(不含)之间的随机数。