Skip to content

Instantly share code, notes, and snippets.

@kyptin
Last active May 12, 2016 18:59
Show Gist options
  • Save kyptin/53a06fea717b00fece65506c06f31c02 to your computer and use it in GitHub Desktop.
Save kyptin/53a06fea717b00fece65506c06f31c02 to your computer and use it in GitHub Desktop.
Make a CDF (cumulative distribution function) from a seq of numbers in Clojure
(defn make-cdf
"Given a seq of numbers, return a plottable vector of [x,y] pairs
representing the cumulative distribution function.
Ex:
(cdf-data [1 2 1 3])
; => [[1 0] [1 1/2] [2 3/4] [3 1]]"
[xs]
{:pre [(sequential? xs)]}
(let [n (count xs)
uniq-xs (->> xs frequencies (into (sorted-map)))
cdf-xs (keys uniq-xs)
n-so-far-seq (reductions + (vals uniq-xs))
cdf-ys (map #(/ % n) n-so-far-seq)
cdf-xy-pairs (map vector cdf-xs cdf-ys)
init-pair [(-> uniq-xs first key) 0]]
(vec (cons init-pair cdf-xy-pairs))))
;; The MIT License (MIT)
;; Copyright (c) 2016 Jeff Terrell
;;
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment