Arc4random random number generator

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?

+4
source share
3 answers

arc4random has an excellent algorithm for generating random numbers based on the current time. There are other functions of rand, but they are not so good and require seeding.

+9
source

When you use arc4random , you avoid one mistake when using % with linear congruent generators (which is the usual algorithm used by rand ): the least significant bits are no less random.

However, you still have truncation problems: i.e. because (1 << 32) % 83 is 77, which means that numbers from 0 to 76 appear (slightly) more often than numbers between 77 and 82. To avoid this, you must throw away the input value (that is, call arc4random again) if it is higher (1 << 32) / 83 * 83 .

(I assume that arc4random range from 0 to 2 32 -1. Edit the explanation above accordingly.)

+13
source

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 used very simple cellular automata as his random number generator for decades in his Mathematica program, so he was very well tested.

+2
source

Source: https://habr.com/ru/post/1332062/


All Articles