Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there're a way to seed Swift 4.2 random number generator

I like the new Swift 4.2 RandomNumberGenerator thing, but I don't see a seed possibility there. Am I missing something, or is there any way at all to seed these generators, by maybe calling an underlying low-level function? I have a lot of code, which uses default number generators on default number types, and I now need to make sure that everything behaves exactly the same between launches with as little code changes as possible.

like image 981
user3537411 Avatar asked Nov 17 '18 04:11

user3537411


2 Answers

If you want reproducibility via explicit seeding you can use the GameplayKit implementation of Mersenne Twister:

import Cocoa
import GameplayKit

let mt = GKMersenneTwisterRandomSource.init(seed: 12345)

for _ in (1...5) {
  print(mt.nextUniform())
}
like image 58
pjs Avatar answered Oct 03 '22 08:10

pjs


The whole idea of the new architecture is that any generator can be substituted just by adopting the RandomNumberGenerator protocol. So if you need a repeatable seed, use your own random generator algorithm.

like image 29
matt Avatar answered Oct 03 '22 09:10

matt