Skip to content

Instantly share code, notes, and snippets.

@SpacyRicochet
Created August 14, 2016 10:40
Show Gist options
  • Select an option

  • Save SpacyRicochet/7a1b1d476405a42b12ce39570ff02de2 to your computer and use it in GitHub Desktop.

Select an option

Save SpacyRicochet/7a1b1d476405a42b12ce39570ff02de2 to your computer and use it in GitHub Desktop.
Uniformly distributed random numbers for @CocoawithLove's Xoroshiro implementation
//
// CwlRandom+NWA.swift
// Butterfly
//
// Created by Bruno Scheele on 10/07/16.
// Copyright © 2016 Noodlewerk Apps V.o.f. All rights reserved.
//
import Foundation
extension Xoroshiro {
/// Calculates a uniform random number less than *upperBound* iff *upperBound* > 0. Else, returns 0.
///
/// - parameter upperBound: The upper bound of the random number.
/// - returns: A random number between 0 and *upperbound*.
/// - note: Adapted from arc4random_uniform to avoid 'modulo bias'.
public mutating func randomUniform(upperbound ub: UInt64) -> UInt64 {
let minimum = UInt64.max % ub
var result: UInt64!
repeat {
result = randomWord()
} while result <= minimum
return result % ub
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment