racket/collects/math/private/distributions/impl/normal-random.rkt
Neil Toronto f2dc2027f6 Initial math library commit. The history for these changes is preserved
in the original GitHub fork:

  https://github.com/ntoronto/racket

Some things about this are known to be broken (most egregious is that the
array tests DO NOT RUN because of a problem in typed/rackunit), about half
has no coverage in the tests, and half has no documentation. Fixes and
docs are coming. This is committed now to allow others to find errors and
inconsistency in the things that appear to be working, and to give the
author a (rather incomplete) sense of closure.
2012-11-16 11:39:51 -07:00

25 lines
1007 B
Racket

#lang typed/racket/base
(require "../../../flonum.rkt"
"../../../base.rkt")
(provide box-muller-transform standard-flnormal-random)
(: box-muller-transform (Float Float -> Float))
(define (box-muller-transform x y)
(cond [(and (fl= x 0.0) (fl= y 0.0)) 0.0]
[else (fl* (flsqrt (fl* -2.0 (fllog x)))
(flsin (fl* (fl* 2.0 pi) y)))]))
(: standard-flnormal-random (-> Float))
;; The Box-Muller method has an bad reputation, but undeservedly:
;; 1. There's nothing unstable about the floating-point implementation of the transform
;; 2. It has good tail behavior (i.e. it can return very unlikely numbers)
;; 3. With today's RNGs, there's no need to worry about generating two random numbers
;; 4. With today's FPUs, there's no need to worry about computing `log' and `sin' (sheesh)
;; Points in favor: it's simple and fast
(define (standard-flnormal-random)
(let loop ()
(define r (box-muller-transform (random) (random)))
(if (rational? r) r (loop))))