Sunday, September 05, 2021

SICP in Clojure: Chapter 1, Exercise 46

This is my Clojure solution to Chapter 1, Exercise 46:

(ns sicp.ch1.ex46
  (:require [sicp.ch1.ex06 :as ch1-ex06]
            [sicp.ch1.ex35 :as ch1-ex35]))

(defn iterative-improve
  [good-enough? improve]
  (fn f [guess]
    (if (good-enough? guess)
      guess
      (f (improve guess)))))

(defn sqrt
  [x]
  ((iterative-improve #(ch1-ex06/good-enough? % x)
                      #(ch1-ex06/improve % x))
   1.0))

(defn fixed-point
  [f first-guess]
  ((iterative-improve #(ch1-ex35/close-enough? % (f %))
                      #(f %))
   first-guess))

(comment
  (sqrt 16) ; => ~4.0

  (sqrt 10000) ; => ~100.0

  (fixed-point #(+ 1 (/ 1 %)) 2.0) ; => ~1.618
  #__)

 

SICP in Clojure: Chapter 1, Exercise 45

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))
  #__)