Skip to content

Instantly share code, notes, and snippets.

@graue
Created August 29, 2012 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graue/3515466 to your computer and use it in GitHub Desktop.
Save graue/3515466 to your computer and use it in GitHub Desktop.
Clojure code to estimate pi
; for some reason it's not finding clojure.contrib.math
;(ns pi-estimator
; (:require clojure.contrib.math))
; this didn't work either:
;(ns pi-estimator
; (:use [clojure.contrib.math :only [abs]]))
(defn abs [x]
(if (>= x 0)
x
(* x -1)))
(defn estimate-pi [tol]
(loop [est 0.0 err 4.0 mul 1 denom 1]
(if (< err tol)
est
(let [new-est (+ est (/ (* 4.0 mul) denom))]
(recur new-est (abs (- new-est est)) (* -1 mul) (+ 2 denom))))))
(println "Pi accurate to five places:" (estimate-pi 0.00001))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment