This is my Clojure solution to Chapter 1, Exercise 45:
(ns sicp.ch1.ex45
(:require [sicp.ch1.ex35 :as ch1-ex35]
[sicp.ch1.ex43 :as ch1-ex43]))
(defn expt
[x n]
(loop [acc 1 n n]
(if (zero? n) acc
(recur (* x acc) (dec n)))))
(defn log2
[n]
(/ (Math/log n) (Math/log 2)))
(defn average-damp
[f]
#(/ (+ % (f %)) 2))
(defn fixed-point
[f guess]
(let [next-guess (f guess)]
(if (ch1-ex35/close-enough? guess next-guess)
next-guess
(fixed-point f next-guess))))
(defn nth-root
[n x]
(fixed-point ((ch1-ex43/repeated average-damp (Math/ceil (log2 n)))
#(/ x (expt % (dec n))))
1.0))
(comment
(nth-root 2 100)
(nth-root 3 1000)
(nth-root 4 10000)
(nth-root 5 100000)
(nth-root 15 (expt 10 15))
#__)
No comments:
Post a Comment