How can I generate large, ranged random numbers in Swift?

后端 未结 1 1846
小鲜肉
小鲜肉 2020-12-04 00:38

I\'m looking for an efficient method of generating large numbers (that includes floating point types!) in Swift, with arbitrary ranges (which may even be UInt.max

相关标签:
1条回答
  • 2020-12-04 01:41

    Here is a possible solution for UInt, Int and Double which works with the full range of those types. It is written as extension methods (now updated for Swift 2), but the same can be done with global functions.

    Note that arc4random_uniform() produces 32-bit numbers only, so that can not be used if Int/UInt are 64-bit integers (which is the case for all OS X machines and all newer iOS devices).

    For UInt we use the technique from https://stackoverflow.com/a/26550169/1187415 (which is just a Swift translation of https://stackoverflow.com/a/10989061/1187415). The case where the range covers the full range of UInt is treated separately.

    extension UInt {
        static func random(minValue minValue : UInt, maxValue : UInt) -> UInt {
            precondition(minValue <= maxValue, "attempt to call random() with minValue > maxValue")
    
            if minValue == UInt.min && maxValue == UInt.max {
                // Random number in the full range of UInt:
    
                var rnd : UInt = 0
                arc4random_buf(&rnd, sizeofValue(rnd))
                return rnd
            } else {
                // Compute random number in the range 0 ... (maxValue-minValue),
                // using the technique from 
                // https://stackoverflow.com/a/26550169/1187415, https://stackoverflow.com/a/10989061/1187415
                // and avoiding the "modulo bias problem":
    
                let range = maxValue - minValue + 1
                let randLimit = UInt.max - UInt.max % range
                var rnd : UInt = 0
                repeat {
                    arc4random_buf(&rnd, sizeofValue(rnd))
                } while rnd >= randLimit
                rnd = rnd % range
    
                // Transform `rnd` back to the range minValue ... maxValue:
                return minValue + rnd
            }
        }
    }
    

    Examples:

    let u1 = UInt.random(minValue: 1000, maxValue: 2000)
    let u2 = UInt.random(minValue: UInt.min, maxValue: UInt.max)
    

    The case of signed integers can be reduced to the unsigned case using the overflow operators and the bitPattern: conversion:

    extension Int {
        static func random(minValue minValue : Int, maxValue : Int) -> Int {
            precondition(minValue <= maxValue, "attempt to call random() with minValue > maxValue")
    
            // Compute unsigned random number in the range 0 ... (maxValue-minValue):
            let diff = UInt(bitPattern: maxValue &- minValue)
            let rnd = UInt.random(minValue: 0, maxValue: diff)
    
            // Transform `rnd` back to the range minValue ... maxValue:
            return minValue &+ Int(bitPattern: rnd)
        }
    }
    

    Examples:

    let i1 = Int.random(minValue: -1000, maxValue: 1000)
    let i2 = Int.random(minValue: Int.min, maxValue: Int.max)
    

    Finally, a straight-forward implementation for Double:

    extension Double {
        static func random(minValue minValue : Double, maxValue : Double) -> Double {
            precondition(minValue <= maxValue, "attempt to call random() with minValue > maxValue")
    
            // Random floating point number in the range 0.0 ... 1.0:
            let rnd = Double(UInt.random(minValue: 0, maxValue: UInt.max))/Double(UInt.max)
    
            // Scale to range minValue ... maxValue:
            return minValue + rnd * (maxValue - minValue)
        }
    }
    

    Example:

    let d = Double.random(minValue: 10.5, maxValue: 123.5)
    

    Update for Swift 3:

    extension UInt {
        static func random(minValue: UInt, maxValue: UInt) -> UInt {
            precondition(minValue <= maxValue, "attempt to call random() with minValue > maxValue")
    
            if minValue == UInt.min && maxValue == UInt.max {
                // Random number in the full range of UInt:
    
                var rnd: UInt = 0
                arc4random_buf(&rnd, MemoryLayout.size(ofValue: rnd))
                return rnd
            } else {
                // Compute random number in the range 0 ... (maxValue-minValue),
                // using the technique from 
                // https://stackoverflow.com/a/26550169/1187415, https://stackoverflow.com/a/10989061/1187415
                // and avoiding the "modulo bias problem":
    
                let range = maxValue - minValue + 1
                let randLimit = UInt.max - UInt.max % range
                var rnd: UInt = 0
                repeat {
                    arc4random_buf(&rnd, MemoryLayout.size(ofValue: rnd))
                } while rnd >= randLimit
                rnd = rnd % range
    
                // Transform `rnd` back to the range minValue ... maxValue:
                return minValue + rnd
            }
        }
    }
    
    extension Int {
        static func random(minValue: Int, maxValue: Int) -> Int {
            precondition(minValue <= maxValue, "attempt to call random() with minValue > maxValue")
    
            // Compute unsigned random number in the range 0 ... (maxValue-minValue):
            let diff = UInt(bitPattern: maxValue &- minValue)
            let rnd = UInt.random(minValue: 0, maxValue: diff)
    
            // Transform `rnd` back to the range minValue ... maxValue:
            return minValue &+ Int(bitPattern: rnd)
        }
    }
    
    extension Double {
        static func random(minValue: Double, maxValue: Double) -> Double {
            precondition(minValue <= maxValue, "attempt to call random() with minValue > maxValue")
    
            // Random floating point number in the range 0.0 ... 1.0:
            let rnd = Double(UInt.random(minValue: 0, maxValue: UInt.max))/Double(UInt.max)
    
            // Scale to range minValue ... maxValue:
            return minValue + rnd * (maxValue - minValue)
        }
    }
    
    0 讨论(0)
提交回复
热议问题