1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 // Exact uniform integers using rejection sampling
17
18 #ifndef TENSORFLOW_LIB_RANDOM_EXACT_UNIFORM_H_
19 #define TENSORFLOW_LIB_RANDOM_EXACT_UNIFORM_H_
20
21 #include <type_traits>
22
23 namespace tensorflow {
24 namespace random {
25
26 template <typename UintType, typename RandomBits>
ExactUniformInt(const UintType n,const RandomBits & random)27 UintType ExactUniformInt(const UintType n, const RandomBits& random) {
28 static_assert(std::is_unsigned<UintType>::value,
29 "UintType must be an unsigned int");
30 static_assert(std::is_same<UintType, decltype(random())>::value,
31 "random() should return UintType");
32 if (n == 0) {
33 // Consume a value anyway
34 // TODO(irving): Assert n != 0, since this case makes no sense.
35 return random() * n;
36 } else if (0 == (n & (n - 1))) {
37 // N is a power of two, so just mask off the lower bits.
38 return random() & (n - 1);
39 } else {
40 // Reject all numbers that skew the distribution towards 0.
41
42 // random's output is uniform in the half-open interval [0, 2^{bits}).
43 // For any interval [m,n), the number of elements in it is n-m.
44
45 const UintType range = ~static_cast<UintType>(0);
46 const UintType rem = (range % n) + 1;
47 UintType rnd;
48
49 // rem = ((2^bits-1) \bmod n) + 1
50 // 1 <= rem <= n
51
52 // NB: rem == n is impossible, since n is not a power of 2 (from
53 // earlier check).
54
55 do {
56 rnd = random(); // rnd uniform over [0, 2^{bits})
57 } while (rnd < rem); // reject [0, rem)
58 // rnd is uniform over [rem, 2^{bits})
59 //
60 // The number of elements in the half-open interval is
61 //
62 // 2^{bits} - rem = 2^{bits} - ((2^{bits}-1) \bmod n) - 1
63 // = 2^{bits}-1 - ((2^{bits}-1) \bmod n)
64 // = n \cdot \lfloor (2^{bits}-1)/n \rfloor
65 //
66 // therefore n evenly divides the number of integers in the
67 // interval.
68 //
69 // The function v \rightarrow v % n takes values from [bias,
70 // 2^{bits}) to [0, n). Each integer in the range interval [0, n)
71 // will have exactly \lfloor (2^{bits}-1)/n \rfloor preimages from
72 // the domain interval.
73 //
74 // Therefore, v % n is uniform over [0, n). QED.
75
76 return rnd % n;
77 }
78 }
79
80 } // namespace random
81 } // namespace tensorflow
82
83 #endif // TENSORFLOW_LIB_RANDOM_EXACT_UNIFORM_H_
84