Skip to content

Instantly share code, notes, and snippets.

@llasram
Forked from timvisher/-
Last active July 30, 2017 17:38

Revisions

  1. llasram revised this gist Jun 25, 2013. 2 changed files with 14 additions and 6 deletions.
    6 changes: 0 additions & 6 deletions -
    Original file line number Diff line number Diff line change
    @@ -1,6 +0,0 @@
    (defn average [n1 n2 & ns]
    (let [ns (into [n1 n2] ns)]
    (/ (apply * ns) (count ns))))

    (apply average (range 1 100))
    ;;; => java.lang.ArithmeticException: integer overflow
    14 changes: 14 additions & 0 deletions mean-sd.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    (defn ^:private mean-sd-step
    [[n m s] ^double x]
    (let [n (long n), m (double m), s (double s)
    n (inc n), d (- x m), m (+ m (/ d n)), s (+ s (* d (- x m)))]
    [n m s]))

    (defn mean-sd
    "Calculate mean and (sample) standard-deviation of `vals`."
    [vals]
    (let [[n m s] (reduce mean-sd-step [0 0.0 0.0] vals)]
    [m (if (<= n 1) 0.0 (Math/sqrt (/ s (dec n))))]))

    (mean-sd (range 1 100))
    ;; => [50.0 28.722813232690143]
  2. @timvisher timvisher created this gist Jun 25, 2013.
    6 changes: 6 additions & 0 deletions -
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    (defn average [n1 n2 & ns]
    (let [ns (into [n1 n2] ns)]
    (/ (apply * ns) (count ns))))

    (apply average (range 1 100))
    ;;; => java.lang.ArithmeticException: integer overflow