Skip to content

Instantly share code, notes, and snippets.

@hyone
Created April 19, 2011 04:38
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 hyone/926820 to your computer and use it in GitHub Desktop.
Save hyone/926820 to your computer and use it in GitHub Desktop.
square root by newton raphson method
(ns newton-raphson
(:use
[clojure.contrib.math :only (abs)]
[clojure.contrib.seq :only (find-first)]))
(defn newton-raphson [improve, init]
(iterate improve init))
(defn within [eps xs]
(second
(find-first
(fn [[a b]] (<= (abs (/ (- a b) b)) eps))
(partition 2 1 xs))))
(defn improve-sqrt [n x]
(/ (+ x (/ n x)) 2))
(defn sqrt-seq-nr [n]
(newton-raphson (partial improve-sqrt n) 1))
(defn sqrt-nr [n eps]
(within eps (sqrt-seq-nr n)))
;; newton-raphson> (take 10 (map double (sqrt-seq-nr 36)))
;; (1.0 18.5 10.22297297297297 6.872226737643129 6.055351744849479 6.000252984119419 6.000000005333189 6.0 6.0 6.0)
;; newton-raphson> (double (sqrt-nr 2 (/ 1 100000)))
;; 1.41421356237469
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment