view src/clojure/contrib/probabilities/random_numbers.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line source
1 ;; Random number generators
3 ;; by Konrad Hinsen
4 ;; last updated May 3, 2009
6 ;; Copyright (c) Konrad Hinsen, 2009. All rights reserved. The use
7 ;; and distribution terms for this software are covered by the Eclipse
8 ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
9 ;; which can be found in the file epl-v10.html at the root of this
10 ;; distribution. By using this software in any fashion, you are
11 ;; agreeing to be bound by the terms of this license. You must not
12 ;; remove this notice, or any other, from this software.
14 (ns
15 ^{:author "Konrad Hinsen"
16 :doc "Random number streams
18 This library provides random number generators with a common
19 stream interface. They all produce pseudo-random numbers that are
20 uniformly distributed in the interval [0, 1), i.e. 0 is a
21 possible value but 1 isn't. For transformations to other
22 distributions, see clojure.contrib.probabilities.monte-carlo.
24 At the moment, the only generator provided is a rather simple
25 linear congruential generator."}
26 clojure.contrib.probabilities.random-numbers
27 (:refer-clojure :exclude (deftype))
28 (:use [clojure.contrib.types :only (deftype)])
29 (:use [clojure.contrib.stream-utils :only (defstream)])
30 (:use [clojure.contrib.def :only (defvar)]))
32 ;; Linear congruential generator
33 ;; http://en.wikipedia.org/wiki/Linear_congruential_generator
35 (deftype ::lcg lcg
36 "Create a linear congruential generator"
37 {:arglists '([modulus multiplier increment seed])}
38 (fn [modulus multiplier increment seed]
39 {:m modulus :a multiplier :c increment :seed seed})
40 (fn [s] (map s (list :m :a :c :seed))))
42 (defstream ::lcg
43 [lcg-state]
44 (let [{m :m a :a c :c seed :seed} lcg-state
45 value (/ (float seed) (float m))
46 new-seed (rem (+ c (* a seed)) m)]
47 [value (assoc lcg-state :seed new-seed)]))
49 ;; A generator based on Clojure's built-in rand function
50 ;; (and thus random from java.lang.Math)
51 ;; Note that this generator uses an internal mutable state.
52 ;;
53 ;; The state is *not* stored in the stream object and can thus
54 ;; *not* be restored!
56 (defvar rand-stream (with-meta 'rand {:type ::rand-stream})
57 "A random number stream based on clojure.core/rand. Note that this
58 generator uses an internal mutable state. The state is thus not stored
59 in the stream object and cannot be restored.")
61 (defstream ::rand-stream
62 [dummy-state]
63 [(rand) dummy-state])