Skip to content

Instantly share code, notes, and snippets.

@trptcolin
Created February 22, 2010 01:04
Show Gist options
  • Save trptcolin/310668 to your computer and use it in GitHub Desktop.
Save trptcolin/310668 to your computer and use it in GitHub Desktop.
;;; Pythagorean Mean computation
;;; Using a lazy sequence to allow for computing the mean at a given point in
;;; an infinite sequence.
;;;
;;; Idea from Clojure mailing list:
;;; (http://groups.google.com/group/clojure/browse_thread/thread/c5b98ef74dc5809f)
;;;
;;; Reference:
;;; http://rosettacode.org/wiki/Averages/Pythagorean_means
(use '[clojure.contrib.math :only (expt)])
(defn- accumulating-over [f id coll]
(drop 1
(iterate (fn [{x :current n :index acc :acc coll :coll}]
{:current (first coll)
:index (inc n)
:acc (f acc (first coll))
:coll (next coll)})
{:current 0 :index 0 :acc id :coll coll})))
(defn a-mean-seq [coll]
(map #(/ (:acc %) (:index %))
(accumulating-over + 0 coll)))
(defn g-mean-seq [coll]
(map #(expt (:acc %) (/ 1 (:index %)))
(accumulating-over * 1 coll)))
(defn h-mean-seq [coll]
(map #(/ (:index %) (:acc %))
(accumulating-over (fn [x y] (+ x (/ 1 y))) 0.0 coll)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment