Skip to content

Commit 522c0e9

Browse files
authored
Merge pull request #5 from ordo-one/uniform-distribution
uniform distribution
2 parents f038cd1 + 5f5c63e commit 522c0e9

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Sources/Random/Uniform.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

0 commit comments

Comments
 (0)