I need generate random numbers in my iPhone game. I using rand() function. But it isn't enough random. I tried using srand with time(Null). But my random generator was periodic. /dev/random isn't an answer because I need new random number each 0.1 sec.
Asked
Active
Viewed 3,792 times
3 Answers
4
On iOS and OS X, use arc4random instead. Higher quality randomness, and no need to worry about seeding.
However, rand()
shouldn't be noticably periodic, unless you're calling srand
each time around. Or using the random numbers incorrectly.

Anomie
- 92,546
- 13
- 126
- 145
-
arc4random() uses /dev/random as source. – JustSid May 06 '11 at 14:33
-
Yes. I call srand() everytime. =( I thought it would solve my problem with rand(). – Riddick May 06 '11 at 14:35
-
1@JustSid: arc4random uses `/dev/urandom` (not `/dev/random`) for the *seed*, and when you manually call `arc4random_stir`. – Anomie May 06 '11 at 14:37
-
1@Riddick: `srand()` should only be called once; think for example what happens if you call `srand(time(NULL))` twice or more within the same second. And in general calling it with `time(NULL)` is not the greatest idea either (it's too predictable), although for a game it probably doesn't matter much. – Anomie May 06 '11 at 14:39
3
You could try random() / srandom() instead. Better generator than rand() / srand().

jv42
- 8,521
- 5
- 40
- 64
0
Are you building for debug or on the simulator? I know I ran into this kind of issue when building some windows applications in debug, the RNG was automatically seeded with a constant value to produce consistent results. You may want to check what it is actually seeded with, and if you are getting different outputs at all each run.

Dan F
- 17,654
- 5
- 72
- 110