|
| 1 | +/* |
| 2 | +Xoroshiro128+ and Xoroshiro128++ pseudorandom number generators (PRNGs). |
| 3 | +*/ |
| 4 | + |
| 5 | +import Accelerate |
| 6 | + |
| 7 | +func rotl(_ x: UInt64, _ k: Int) -> UInt64 { |
| 8 | + (x &<< k) | (x &>> (64 &- k)) |
| 9 | +} |
| 10 | + |
| 11 | +/// Xoroshiro128+ is a 64-bit pseudorandom number generator (PRNG) for double-precision values. |
| 12 | +public struct Xoroshiro128Plus: RandomNumberGenerator { |
| 13 | + private var state: (UInt64, UInt64) |
| 14 | + |
| 15 | + public init(seed: (UInt64, UInt64)? = nil) { |
| 16 | + let a = UInt64.random(in: 0..<UInt64.max) |
| 17 | + let b = UInt64.random(in: 0..<UInt64.max) |
| 18 | + state = seed ?? (a, b) |
| 19 | + } |
| 20 | + |
| 21 | + public mutating func next() -> UInt64 { |
| 22 | + let s0 = state.0 |
| 23 | + var s1 = state.1 |
| 24 | + let result = s0 &+ s1 |
| 25 | + |
| 26 | + s1 ^= s0 |
| 27 | + state.0 = rotl(s0, 24) ^ s1 ^ (s1 << 16) |
| 28 | + state.1 = rotl(s1, 37) |
| 29 | + |
| 30 | + return result |
| 31 | + } |
| 32 | + |
| 33 | + /// Generate a random double-precision value from a uniform distribution over [0, 1) which includes zero but |
| 34 | + /// excludes one. |
| 35 | + /// - Returns: Random double-precision value. |
| 36 | + public mutating func next() -> Double { |
| 37 | + Double(next() >> 11) * 0x1.0p-53 |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/// Xoroshiro128++ is a 64-bit pseudorandom number generator (PRNG) for double-precision values. |
| 42 | +public struct Xoroshiro128PlusPlus: RandomNumberGenerator { |
| 43 | + private var state: (UInt64, UInt64) |
| 44 | + |
| 45 | + public init(seed: (UInt64, UInt64)? = nil) { |
| 46 | + let a = UInt64.random(in: 0..<UInt64.max) |
| 47 | + let b = UInt64.random(in: 0..<UInt64.max) |
| 48 | + state = seed ?? (a, b) |
| 49 | + } |
| 50 | + |
| 51 | + public mutating func next() -> UInt64 { |
| 52 | + let s0 = state.0 |
| 53 | + var s1 = state.1 |
| 54 | + let result = rotl(s0 &+ s1, 17) &+ s0 |
| 55 | + |
| 56 | + s1 ^= s0 |
| 57 | + state.0 = rotl(s0, 49) ^ s1 ^ (s1 << 21) |
| 58 | + state.1 = rotl(s1, 28) |
| 59 | + |
| 60 | + return result |
| 61 | + } |
| 62 | + |
| 63 | + /// Generate a random double-precision value from a uniform distribution over [0, 1) which includes zero but |
| 64 | + /// excludes one. |
| 65 | + /// - Returns: Random double-precision value. |
| 66 | + public mutating func next() -> Double { |
| 67 | + Double(next() >> 11) * 0x1.0p-53 |
| 68 | + } |
| 69 | +} |
0 commit comments