Skip to content

Commit 5644a7c

Browse files
authored
Switch back to ordinary rejection sampling for random-natural (#111)
1 parent 21e324f commit 5644a7c

File tree

1 file changed

+2
-9
lines changed

1 file changed

+2
-9
lines changed

math-lib/math/private/base/base-random.rkt

+2-9
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
[else r]))]))
2525

2626
(define random-max 4294967087)
27-
(define bias-bits (* 2 block-bits))
2827

2928
(: random-natural (Integer -> Natural))
3029
;; Returns a random integer in the interval [0..n)
@@ -33,15 +32,9 @@
3332
[(n . <= . 0) (raise-argument-error 'random-natural "Positive-Integer" n)]
3433
[(n . <= . random-max) (random n)]
3534
[else
36-
;; Rejection sampling has rejection probability approaching 1/2 in the worst cases; that is,
37-
;; when n = 1+2^i for some large-ish integer i
38-
;; Adding extra bits shrinks the rejection probability to near zero (it approaches
39-
;; (* 1/2 (expt 2 (- bias-bits)))), at the cost of some bias
40-
;; The bias starts become detectable after taking (expt 2 bias-bits) samples, which is plenty
41-
(define bits (+ bias-bits (integer-length (- n 1))))
42-
(define m (arithmetic-shift 1 bits))
35+
(define bits (integer-length (- n 1)))
4336
(let loop ()
44-
(define r (quotient (* (+ (random-bits bits) 1) n) m))
37+
(define r (random-bits bits))
4538
(if (r . >= . n) (loop) r))]))
4639

4740
(: random-integer (Integer Integer -> Integer))

0 commit comments

Comments
 (0)