arc4random Random Number Generator

僤鯓⒐⒋嵵緔 提交于 2019-12-21 18:43:18

问题


int randomNumber = (arc4random() % 83) + 1;

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?


回答1:


arc4random has a superior algorithm for generating random numbers based on the current time. There are other rand functions but they are not as good and require seeding.




回答2:


When you use arc4random you avoid one pitfall of using % with linear congruential generators (which is the usual algorithm used by rand): the low-order bits aren't less random.

However, you still have truncation issues: i.e., because (1 << 32) % 83 is 77, that means that numbers between 0 and 76 appear (slightly) more frequently than numbers between 77 and 82. To avoid this, you should throw away the incoming value (i.e., call arc4random again) if it's above (1 << 32) / 83 * 83.

(I assume the range of arc4random is from 0 to 232-1. Adjust the above explanation accordingly.)




回答3:


The best random number generator I've ever seen (as well as a very clear definition of what random means) can be found in Stephen Wolfram's A New Kind of Science. He's been using a very simple cellular automata as his random number generator for decades in his Mathematica software program so it's been extremely well tested.



来源:https://stackoverflow.com/questions/4435905/arc4random-random-number-generator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!