Created
June 8, 2022 13:33
-
-
Save matthewdowney/81ab7fa53bf49da0c17d8d264575f5e9 to your computer and use it in GitHub Desktop.
Sample from Poisson distribution in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn poisson | |
"Return a function that samples from a Poisson distribution using Knuth's | |
algorithm[^1], given `lambda`, the expected number of occurrences per | |
interval. | |
[^1]: https://en.wikipedia.org/wiki/Poisson_distribution#Random_drawing_from_the_Poisson_distribution" | |
([lambda] | |
(poisson lambda (Random.))) | |
([lambda ^Random r] | |
(let [l (Math/exp (- lambda))] | |
(fn [] | |
(loop [k (int 0) p (float 1)] | |
(let [p (* p (.nextFloat ^Random r))] | |
(if (> p l) | |
(recur (inc k) p) | |
k))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment