Created
March 22, 2016 05:47
-
-
Save DavidYKay/0eb773ae353a2c5ae5e5 to your computer and use it in GitHub Desktop.
Implementation of the square root function, based on SICP Lecture 1A
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 example.square-root) | |
(def tolerance 0.00000000001) | |
(defn square [x] | |
(* x x)) | |
(defn avg [& args] | |
(/ (apply + args) | |
(count args))) | |
(defn abs [x] | |
(if (>= x 0) | |
x | |
(- x))) | |
(defn improve-guess [g x] | |
(avg g (/ x g))) | |
(defn close-enough? [g x] | |
(< (abs (- x (square g))) | |
tolerance)) | |
(defn attempt [g x] | |
(if (close-enough? g x) | |
g | |
(attempt (improve-guess g x) x))) | |
(defn square-root [x] | |
(attempt 1 x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment