mardi 6 janvier 2015

arc4random() and arc4random_unofrm() not really random?

I have been using arc4random() and arc4random_uniform() and I always had the feeling that they wasn't exactly random, for example, I was "randomly" choosing values from an Array but often the values that came out were the same when I generated them multiple times in a row, so today I thought that I would use an Xcode playground to see how these functions are behaving, so I first tests arc4random_uniform to generate a number between 0 and 4, so I used this algorithm :



import Cocoa

var number = 0

for i in 1...20 {
number = Int(arc4random_uniform(5))
}


And I ran it several times, and here is how to values are evolving most of the time :

enter image description here enter image description here


So as you can see the values are increasing and decreasing repeatedly, and once the values are at the maximum/minimum, they often stay at it during a certain time (see the first screenshot at the 5th step, the value stays at 3 during 6 steps, the problem is that it isn't at all unusual, the function actually behaves in that way most of the time in my tests.


Now, if we look at arc4random(), it's basically the same :

enter image description here enter image description here


So here are my questions :



  • Why is this function behaving in this way ?

  • How to make it more random ?


Thank you.





Aucun commentaire:

Enregistrer un commentaire