Sunday, June 14, 2020

SICP in Clojure: Chapter 1, Exercise 36

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

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

(defn try-guess
  [f guess]
  (let [next-guess (f guess)]
    (println (double next-guess))
    (if (ch1-ex35/close-enough? guess next-guess)
      next-guess
      (try-guess f next-guess))))

(defn fixed-point
  [f first-guess]
  (try-guess f first-guess))

(defn try-guess-with-avg-damping
  [f guess]
  (let [next-guess (f guess)]
    (println (double next-guess))
    (if (ch1-ex35/close-enough? guess next-guess)
      next-guess
      (try-guess-with-avg-damping f (/ (+ next-guess guess) 2)))))

(defn fixed-point-with-avg-damping
  [f first-guess]
  (try-guess-with-avg-damping f first-guess))

(double (fixed-point #(/ (Math/log 1000) (Math/log %))
                     1.1)) ; => 4.555538934848503 -- 38 steps

(double (fixed-point-with-avg-damping #(/ (Math/log 1000)
                                          (Math/log %))
                                      1.1))
                                        ; => 4.555533149860501 in 14
                                        ; steps
 

No comments: