;;;; srfi-27-normals.scm ;;;; Kon Lovett, Dec '17 ;;;; Kon Lovett, Jun '17 ;;;; Kon Lovett, May '06 ; Chicken Generic Arithmetic! (could use fp routines) (module srfi-27-normals (;export *make-random-normals make-random-normals) (import scheme chicken) (use (only type-errors error-argument-type) (only type-checks define-check+error-type check-procedure check-cardinal-integer check-real check-open-interval check-closed-interval) srfi-27 srfi-27-distributions-support) ;;; Normal distribution ;; Knuth's "The Art of Computer Programming", Vol. II, 2nd ed., ;; Algorithm P of Section 3.4.1.C. (define (*make-random-normals mu sigma randoms) (let ((next #f)) (lambda () (if next (let ((result next)) (set! next #f) (+ mu (* sigma result))) (let loop () (let* ( (v1 (- (* 2.0 (randoms)) 1.0) ) (v2 (- (* 2.0 (randoms)) 1.0) ) (s (+ (* v1 v1) (* v2 v2)) ) ) ; (if (<= 1.0 s) (loop) (let ((scale (sqrt (/ (* -2.0 (log s)) s)))) (set! next (* scale v2)) (+ mu (* sigma scale v1))))))))) ) (define (make-random-normals #!key (mu 0.0) (sigma 1.0) (randoms (random-real/current))) (check-real 'make-random-normals mu 'mu) (check-nonzero-real 'make-random-normals sigma 'sigma) (check-procedure 'make-random-normals randoms 'randoms) (values (*make-random-normals mu sigma randoms) (lambda () (values mu sigma randoms))) ) ) ;module srfi-27-normals