Skip to content

Instantly share code, notes, and snippets.

@kahunamoore
Forked from arnaudbos/∪_prob.clj
Created March 23, 2018 05:25
Show Gist options
  • Select an option

  • Save kahunamoore/9e6975bebceb6bfe6194d98762d17d65 to your computer and use it in GitHub Desktop.

Select an option

Save kahunamoore/9e6975bebceb6bfe6194d98762d17d65 to your computer and use it in GitHub Desktop.
Inclusion–Exclusion Principle for probabilities in Clojure.
(require '[clojure.math.combinatorics :refer [combinations]])
(defn ∩-prob
[a & more]
(reduce * a more))
(defn ∪-prob [a b & more]
"https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle#In_probability"
(let [ps (concat [a b] more)
n (count ps)]
(loop [k 1 prev 0]
(if (> k n)
prev
(let [pow (+ k 1)
mult (Math/pow -1 pow)
cs (combinations ps k)
intersections (map #(* mult (apply ∩-prob %)) cs)]
(recur (inc k) (reduce + prev intersections)))))))
(∪-prob 0.7 0.5 0.3 0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment