Created
April 19, 2011 04:38
-
-
Save hyone/926820 to your computer and use it in GitHub Desktop.
square root by newton raphson method
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
(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