| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -176,30 +176,29 @@ function randomInt(min, max, callback) { | |||
| 176 | 176 | `<= ${RAND_MAX}`, range); | |
| 177 | 177 | } | |
| 178 | 178 | ||
| 179 | - const excess = RAND_MAX % range; | ||
| 180 | - const randLimit = RAND_MAX - excess; | ||
| 179 | + // For (x % range) to produce an unbiased value greater than or equal to 0 and | ||
| 180 | + // less than range, x must be drawn randomly from the set of integers greater | ||
| 181 | + // than or equal to 0 and less than randLimit. | ||
| 182 | + const randLimit = RAND_MAX - (RAND_MAX % range); | ||
| 181 | 183 | ||
| 182 | 184 | if (isSync) { | |
| 183 | 185 | // Sync API | |
| 184 | 186 | while (true) { | |
| 185 | 187 | const x = randomBytes(6).readUIntBE(0, 6); | |
| 186 | - // If x > (maxVal - (maxVal % range)), we will get "modulo bias" | ||
| 187 | - if (x > randLimit) { | ||
| 188 | - // Try again | ||
| 188 | + if (x >= randLimit) { | ||
| 189 | + // Try again. | ||
| 189 | 190 | continue; | |
| 190 | 191 | } | |
| 191 | - const n = (x % range) + min; | ||
| 192 | - return n; | ||
| 192 | + return (x % range) + min; | ||
| 193 | 193 | } | |
| 194 | 194 | } else { | |
| 195 | 195 | // Async API | |
| 196 | 196 | const pickAttempt = () => { | |
| 197 | 197 | randomBytes(6, (err, bytes) => { | |
| 198 | 198 | if (err) return callback(err); | |
| 199 | 199 | const x = bytes.readUIntBE(0, 6); | |
| 200 | - // If x > (maxVal - (maxVal % range)), we will get "modulo bias" | ||
| 201 | - if (x > randLimit) { | ||
| 202 | - // Try again | ||
| 200 | + if (x >= randLimit) { | ||
| 201 | + // Try again. | ||
| 203 | 202 | return pickAttempt(); | |
| 204 | 203 | } | |
| 205 | 204 | const n = (x % range) + min; | |
| Back | FazBrowse Home | New Git URL |
0 commit comments