views:

2558

answers:

2

I was using the arc4random() function in order to generate a random group and sequence of numbers, but I was told that this was overkill and that I should use the random() function instead. However, the random() function gives me the same group and sequence of numbers every time.

I call srand(time(0)) once when my app first starts in order to seed the random() function. Do you ever need to reseed the random() function?

Am I missing something?

Thanks.

+1  A: 

No, you do not need to reseed the random number generator. There is some additional uniformity gained by generating some amount of numbers and throwing them away, but unless you are looking for security level random number generation there is no need. For most purposes a properly seeded random number generator is uniform enough.

groundhog
+3  A: 

First off, who told you arc4random was overkill? I use it in my projects, and it (a) satisfies my requirements, (b) doesn't suck down resources (at least any visible to the user or obvious to me), and (c) was trivial to implement, so I don't really see how a similar use in your own code could be called "overkill."

Second, srand() seeds the rand() function, not random(), so that may be your issue. And no, you shouldn't have to reseed the generator at any time during your program's execution - once during startup is enough.

Tim
How do you seed the random() function then?
schwabrX
Try the function `randomize()`.
Tim
arc4random() is not overkill, and will give you substantially better results than random().
Rob Keniger
I went and tried some actual code, and between that and other comments I found a couple things: 1. `randomize()` does indeed seed the `random()` function; 2. Apparently Snow Leopard doesn't include `randomize()` in its `stdlib.h` like I expected; 3. You should use `arc4random()` in any event.
Tim