5

In Swift 2, we could use srand and rand or random (and probably others) to seed random numbers.

Unfortunately, this does not work in Swift 3. Trying to use any of these functions results in an error message:

error: 'random()' is unavailable in Swift: Use arc4random instead.

arc4_random is great but, I can't seed it manually.

The other option (from the previous SO post) is to use the GameKit framework. It feels like overkill (not to mention not cross-platform and not Swift only) to import a whole Framework for random number seeding.

Is there an alternative?

Community
  • 1
  • 1
Edward Loveall
  • 1,983
  • 1
  • 19
  • 34
  • This seems to be a virtual duplicate of the question that you link to. If what you want it your own seedable pseudorandom number generator, you could implement a garden-variety linear congruential generator requiring not much code. – John Coleman Sep 14 '16 at 18:00
  • @JohnColeman Why implement your own LCG when GameKit provides Mersenne Twister, which is seedable and better than any LCG? – pjs Sep 14 '16 at 18:17
  • I'm curious, why would you like to seed it manually? `arc4random` automatically reseeds itself from the kernel's random device. – Alexander Sep 14 '16 at 18:18
  • 1
    @pjs My assumption was that the most plausible reason to want to seed a generator manually is to get a reproducible stream of random numbers for testing purposes. If so, an LCG is more than adequate. After testing, you could simply replace the calls to the LCG with calls to `arc4_random` Also, OP seemed to want to avoid `GameKit`. – John Coleman Sep 14 '16 at 18:25
  • @JohnColeman LCGs have known distributional issues, and while debugging is a good reason to want reproducibility, it's not the only one. Scientific journals want your stochastic simulation model results to be reproducible by referees and readers. Many people also use correlation induction strategies to achieve [variance reduction](https://en.wikipedia.org/wiki/Variance_reduction). I guess I fundamentally don't see the point of avoiding GameKit. It's there, it works, it's portable and reproducible, and it provides better better random numbers more reliably than roll-your-own solutions. – pjs Sep 14 '16 at 18:52
  • @pjs Good points. – John Coleman Sep 14 '16 at 18:53
  • @AlexanderMomchliov pretty much what john said but I'm using it for drawing random landscapes and wanted to try out different algorithms on the same set of random data. I suppose I could store the output of arc4_random but, again, seeded random seems like the best solution. But after all this, maybe not. Either way, predictable randomness is a useful thing. – Edward Loveall Sep 14 '16 at 18:58
  • 1
    @EdwardLoveall Try srand48() and drand48() – Swifty Sep 14 '16 at 19:22

0 Answers0