1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger {
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate a floating-point value within a specific
/// range when you are using a custom random number generator. This example
/// creates three new values in the range `10.0 ..< 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ..< 20.0, using: &myGenerator))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random(in:using:)` static method chooses a random value from a
/// continuous uniform distribution in `range`, and then converts that value
/// to the nearest representable value in this type. Depending on the size
/// and span of `range`, some concrete values may be represented more
/// frequently than others.
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of floating-point values each time you run your program,
/// that sequence may change when your program is compiled using a
/// different version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// `range` must be finite and non-empty.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
let delta = range.upperBound - range.lowerBound
// TODO: this still isn't quite right, because the computation of delta
// can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and
// .lowerBound = -.upperBound); this should be re-written with an
// algorithm that handles that case correctly, but this precondition
// is an acceptable short-term fix.
_precondition(
delta.isFinite,
"There is no uniform distribution on an infinite range"
)
let rand: Self.RawSignificand
if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 {
rand = generator.next()
} else {
let significandCount = Self.significandBitCount + 1
let maxSignificand: Self.RawSignificand = 1 << significandCount
// Rather than use .next(upperBound:), which has to work with arbitrary
// upper bounds, and therefore does extra work to avoid bias, we can take
// a shortcut because we know that maxSignificand is a power of two.
rand = generator.next() & (maxSignificand - 1)
}
let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2)
let randFloat = delta * unitRandom + range.lowerBound
if randFloat == range.upperBound {
return Self.random(in: range, using: &generator)
}
return randFloat
}
/// Returns a random value within the specified range.
///
/// Use this method to generate a floating-point value within a specific
/// range. This example creates three new values in the range
/// `10.0 ..< 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ..< 20.0))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random()` static method chooses a random value from a continuous
/// uniform distribution in `range`, and then converts that value to the
/// nearest representable value in this type. Depending on the size and span
/// of `range`, some concrete values may be represented more frequently than
/// others.
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// `range` must be finite and non-empty.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: Range<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate a floating-point value within a specific
/// range when you are using a custom random number generator. This example
/// creates three new values in the range `10.0 ... 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ... 20.0, using: &myGenerator))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random(in:using:)` static method chooses a random value from a
/// continuous uniform distribution in `range`, and then converts that value
/// to the nearest representable value in this type. Depending on the size
/// and span of `range`, some concrete values may be represented more
/// frequently than others.
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of floating-point values each time you run your program,
/// that sequence may change when your program is compiled using a
/// different version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value. Must be finite.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
let delta = range.upperBound - range.lowerBound
// TODO: this still isn't quite right, because the computation of delta
// can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and
// .lowerBound = -.upperBound); this should be re-written with an
// algorithm that handles that case correctly, but this precondition
// is an acceptable short-term fix.
_precondition(
delta.isFinite,
"There is no uniform distribution on an infinite range"
)
let rand: Self.RawSignificand
if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 {
rand = generator.next()
let tmp: UInt8 = generator.next() & 1
if rand == Self.RawSignificand.max && tmp == 1 {
return range.upperBound
}
} else {
let significandCount = Self.significandBitCount + 1
let maxSignificand: Self.RawSignificand = 1 << significandCount
rand = generator.next(upperBound: maxSignificand + 1)
if rand == maxSignificand {
return range.upperBound
}
}
let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2)
let randFloat = delta * unitRandom + range.lowerBound
return randFloat
}
/// Returns a random value within the specified range.
///
/// Use this method to generate a floating-point value within a specific
/// range. This example creates three new values in the range
/// `10.0 ... 20.0`.
///
/// for _ in 1...3 {
/// print(Double.random(in: 10.0 ... 20.0))
/// }
/// // Prints "18.1900709259179"
/// // Prints "14.2286325689993"
/// // Prints "13.1485686260762"
///
/// The `random()` static method chooses a random value from a continuous
/// uniform distribution in `range`, and then converts that value to the
/// nearest representable value in this type. Depending on the size and span
/// of `range`, some concrete values may be represented more frequently than
/// others.
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value. Must be finite.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: ClosedRange<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
|