Skip to content

Instantly share code, notes, and snippets.

@matthewdowney
Created June 8, 2022 13:33
Show Gist options
  • Save matthewdowney/81ab7fa53bf49da0c17d8d264575f5e9 to your computer and use it in GitHub Desktop.
Save matthewdowney/81ab7fa53bf49da0c17d8d264575f5e9 to your computer and use it in GitHub Desktop.
Sample from Poisson distribution in Clojure
(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