Skip to content

Instantly share code, notes, and snippets.

@arnaudbos
Last active March 25, 2018 00:26
Show Gist options
  • Select an option

  • Save arnaudbos/59ab26bb6958f07fbc78ef3661572773 to your computer and use it in GitHub Desktop.

Select an option

Save arnaudbos/59ab26bb6958f07fbc78ef3661572773 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)]
(transduce (comp (map #(combinations ps %))
(map (fn [cs]
(transduce
(map #(apply ∩-prob %))
+
cs)))
(map-indexed #(* %2 (Math/pow -1 (+ 2 %1)))))
+
(range 1 (inc n))
)))
(∪-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