schwabrX
schwabrX

Reputation:

Generating Random Numbers in Objective C for iPhone SDK

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.

Upvotes: 5

Views: 5165

Answers (2)

Tim
Tim

Reputation: 60150

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.

Upvotes: 4

groundhog
groundhog

Reputation: 4780

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.

Upvotes: 2

Related Questions