Saturday, August 10, 2019

SICP in Clojure: Chapter 1, Exercise 15

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

(ns sicp.ch1.ex15)

(defn cube
  [x]
  (* x x x))

(defn p
  [x]
  (- (* 3 x) (* 4 (cube x))))

(defn sine
  [angle]
  (if (not (> (Math/abs angle) 0.1))
    angle
    (p (sine (/ angle 3.0)))))

(sine 12.15) ; => -0.39 -- p is applied 5 times

;; if a is the angle then the space complexity (or the maximum height
;; of the tree) is O(log a) else the time complexity (or the number of
;; nodes in the tree) is also O(log a)

No comments: