Skip to content

Instantly share code, notes, and snippets.

@igalshilman
Created December 7, 2013 11:25
Show Gist options
  • Save igalshilman/7839968 to your computer and use it in GitHub Desktop.
Save igalshilman/7839968 to your computer and use it in GitHub Desktop.
(defprotocol RandomOperations
(uniform [this])
(exponential [this rate])
(normal [this avg stddev])
(geometric [this rate]))
(extend-protocol RandomOperations
java.util.Random
(uniform [this]
(.nextDouble this))
(exponential [this rate]
(let [u (- 1 (uniform this))]
(/ (Math/log ^double u) (- ^double rate))))
(normal [this avg stddev]
(+ avg
(* stddev
(.nextGaussian this))))
(geometric [this rate]
(let [l (Math/exp (- rate))]
(loop [k 1
p (uniform this)]
(if (< p l)
(dec k)
(recur (inc k) (* p (uniform this)))))))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment