Created
August 17, 2020 21:05
-
-
Save infotroph/a37850c7cbaeb1b339df97ec7537e350 to your computer and use it in GitHub Desktop.
Scaling an 7-state RNG to uniform integers on an arbitrary range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# in R: | |
rng_7 <- function(n) { | |
sample(0:6, size = n, replace = TRUE) | |
} | |
scale_rng <- function(m, n) { | |
range <- n - m | |
n_digits <- ceiling(log10(range) / log10(7)) | |
exponents <- seq(from = n_digits - 1, to = 0) | |
proposal <- n+1 | |
while (proposal > range) { | |
digits <- rng_7(n_digits) | |
proposal <- sum(digits * 7^exponents) | |
} | |
proposal + m | |
} | |
------- | |
# in Python: | |
from random import randint | |
from math import log10, ceil | |
def rng_7(n): | |
return [randint(0, 6) for i in range(n)] | |
def scale_rng(m, n): | |
interval = n - m | |
n_digits = ceil(log10(interval) / log10(7)) | |
exponents = range(n_digits - 1, -1, -1) | |
proposal = interval + 1 | |
while(proposal > interval): | |
digits = rng_7(n_digits) | |
proposal = sum([d * 7**x for d,x in zip(digits, exponents)]) | |
return proposal + m | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment