Last active
August 29, 2015 14:07
-
-
Save taylorlapeyre/827d4ad26ea5a1560559 to your computer and use it in GitHub Desktop.
Answer
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
(defn abs [x] | |
"Returns x if the number is > 0, otherwise -x" | |
(if (neg? x) (- x) x)) | |
(defn square [x] | |
"Squares the number" | |
(* x x)) | |
(defn cube [x] | |
"Multiplies the square of the number by itself" | |
(* (square x) x)) | |
(defn good-enough? [guess x] | |
"Returns true if the cube of the guess is less than | |
the predefined tolerance (0.001)" | |
(< | |
(abs (- (cube guess) x)) | |
0.001)) | |
(defn improve [guess x] | |
"Applies the formula of newton's method for cube roots | |
to the guess and number" | |
(/ | |
(+ | |
(/ x (square guess)) | |
(* 2 guess)) | |
3)) | |
(defn cbrt-iter [guess x] | |
"Recursively apply newton's method until the result is acceptable" | |
(if (good-enough? guess x) | |
guess | |
(cbrt-iter (improve guess x) x))) | |
(defn cbrt [x] | |
"Returns the cube root of a number via newton's method | |
with a default guess of 1" | |
(cbrt-iter 1.0 x)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment