Created
December 14, 2010 11:52
-
-
Save kirankulkarni/740316 to your computer and use it in GitHub Desktop.
Finds nthroot of given number
This file contains hidden or 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 kk_samples.nthroot) | |
(defn abs | |
"Calculate the absolute value of number" | |
[n] | |
(if (neg? n) | |
(* -1 n) | |
n)) | |
(defn pow | |
"Calculates nth power of a number" | |
[number exponent] | |
(if (zero? exponent) | |
1 | |
(* number (pow number (- exponent 1))))) | |
(defn isroot? | |
"Tests if root is close enough to real nth root of number" | |
[number n root] | |
(let [diff (- (pow root n) number)] | |
(if (< (abs diff) 0.001) | |
true | |
false))) | |
(defn nthroot | |
"finds the nthroot of the given number" | |
[number n] | |
(loop [root 1.0] | |
(if(isroot? number n root) | |
root | |
(recur (/ (+ (* root (- n 1)) (/ number (pow root (- n 1)))) n))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment