File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import RealModule
2+
3+ /// Uniform distribution implementation with stochastic rounding.
4+ @frozen public struct Uniform {
5+ public let n : Int64
6+ public let p : Double
7+
8+ @inlinable init ( n: Int64 , p: Double ) {
9+ self . n = n
10+ self . p = p
11+ }
12+ }
13+ extension Uniform {
14+ /// Create a uniform distribution with the given parameters. Using values of ``p`` greater
15+ /// than 0.5 is not recommended, as it could distort the mean of the distribution.
16+ @inlinable public static subscript( n: Int64 , p: Double ) -> Self { . init( n: n, p: p) }
17+ }
18+ extension Uniform {
19+ @inlinable public func sample( using generator: inout some RandomNumberGenerator ) -> Int64 {
20+ let n : Double = . init( self . n)
21+ let x : Double = . random( in: 0 ... 2 * n * self . p, using: & generator)
22+ let i : Int64 = . init( x)
23+ let f : Double = x - Double. init ( i)
24+ let r : Int64 = Double . random ( in: 0 ..< 1 , using: & generator) < f ? 1 : 0
25+ return min ( self . n, i + r)
26+ }
27+ }
You can’t perform that action at this time.
0 commit comments