Created
August 29, 2012 16:46
-
-
Save graue/3515466 to your computer and use it in GitHub Desktop.
Clojure code to estimate pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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