Created
March 13, 2024 20:48
-
-
Save JadenGeller/d2601176aa1566d56d186bb09f848b42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Float32 { | |
public static func gaussianRandomPair(using generator: inout some RandomNumberGenerator) -> (Float32, Float32) { | |
let u1 = Float.random(in: 0..<1, using: &generator) | |
let u2 = Float.random(in: 0..<1, using: &generator) | |
let r = sqrt(-2 * log(u1)) | |
let theta = 2 * Float.pi * u2 | |
let z0 = r * cos(theta) | |
let z1 = r * sin(theta) | |
return (z0, z1) | |
} | |
} | |
public struct GaussianDistributionSampler { | |
public init() {} | |
var extra: Float? | |
public mutating func next(using generator: inout some RandomNumberGenerator) -> Float { | |
if let extra { | |
self.extra = nil | |
return extra | |
} else { | |
let (first, second) = Float.gaussianRandomPair(using: &generator) | |
self.extra = second | |
return first | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment