开发者

How to obtain high quality random numbers on the iPhone or iPad?

I know arc4random() is considered to be one of the best options开发者_如何转开发 for randomness. But still, it tends to give obvious duplicates and repetitions at some times.

I thought of using the accelerometers to add some real randomness to the output of arc4random.Before I spend some weeks in developing a better solution: Which other solutions are available?


Duplicates and repetitions are expected from a random stream of numbers. Trying to add "more randomness" is not needed; arc4random already reads from /dev/urandom, which gathers entropy from various sources in the system.


If you are trying to get rid of duplicates and repetitions (especially from arc4random sequences of less than millions in length), you will probably end up with a much less random sequence. It's a common human mental error to expect less repetitions in true randomness.

If you don't want duplicates for some purpose, you should do a random sort of an array with no duplicate elements, as in a card shuffle.


In answer to your actual question, if you want something better than arc4random(), look in to the

mersenne twister

which, in certain senses, is "better". Hope it helps!


I also urge anyone who is new to the topic to read one of the most famous answers on stack overflow, which explains distributions nicely, with graphs even!

Understanding "randomness"

"Never, ever add or multiply random numbers in an attempt to get 'better' randomness," is the short version.


IF you wish to cycle through your list "seemingly" randomly and avoid repeating any item ... use arc4random() and after each item has been viewed, removed it from list. When list runs dry, reload it.

Ex:

if (!self.dictionaryValues) {
[self loadList];

} else {

NSMutableDictionary *unusedValueList = [[NSMutableDictionary alloc] initWithDictionary:self.dictionaryValues];

int random = arc4random()%[self.dictionaryValues count]; // note, crashes on nil;
int i=0;
for (NSString *key in self.dictionaryValues) {
        i++;
        if (i == random) {
            NSLog(@"MATCH! on key=%@", key);
            [unusedValueList removeObjectForKey:key];
        }
}
self.dictionaryValues = nil;
self.dictionaryValues = unusedValueList;

}

hope this helps!


I had a long answer here, but I'm just going to link to this. Because it basically sums up everything that's wrong about trying to make random numbers 'more random'

http://thedailywtf.com/Articles/More-Entropy,-Please.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜