vendredi 10 avril 2015

What is the Swift equivalent of Java's Random class (isolated PRNG)

Most discussions of random number generation in Swift talk about arc4random() and other standard C functions that produce a global sequences of random numbers. In some cases it is useful to have an isolated pseudorandom number generator that provides separate, reproducible streams of numbers. e.g. in a game you may wish to have a reproducible random sequences for two aspects of the game and the order in which the two are called should not change the respective streams.


Answer:


The rand_r() function accomplishes this by operating on its own seed value to maintain state. Here is a simple example of how one could mimic the Java Random class with this.



/** Java style PRNG */
public class Random
{
var seed : UInt32 = 0

init( _ seed : UInt32 ) {
self.seed = seed
}

/** float 0-1.0 */
public func nextFloat() -> Float {
return Float(rand_r(&seed)) / Float(INT32_MAX);
}

}




Aucun commentaire:

Enregistrer un commentaire