]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_39.clj
solutions to 4.38, 4.39 and 4.40
[sicp.git] / src / sicp / ex1_39.clj
1 (ns sicp.ex1_39
2   (:use [sicp utils ex1_37]
3         [clojure.contrib test-is]))
4
5 ;; approximating tangent using lambert's cont fract
6 ;; if you look at the formula, -xtan (x) = -x^2/(1-(x^2/3-x^2/5-.... ))
7 (defn tan-approximation [x len]
8   (* (/ -1.0 x) 
9      (cont-frac (fn [k] (* -1.0 (square x)))
10                 (fn [k] (- (* 2 k) 1))
11                 len)))
12
13 (comment
14 user> (tan-approximation (/ Math/PI 4) 20)
15 1.0
16 user> (Math/tan (/ Math/PI 4))
17 0.9999999999999999
18 user> (Math/tan (/ Math/PI 10))
19 0.3249196962329063
20 user> (tan-approximation (/ Math/PI 10) 20)
21 0.32491969623290634
22 user> (tan-approximation Math/PI 20)
23 -1.4135798584282297E-16
24 user> (Math/tan Math/PI)
25 -1.2246467991473532E-16
26 user> (Math/tan (/ Math/PI 2.0))
27 1.633123935319537E16
28 user> (tan-approximation (/ Math/PI 2) 20)
29 ; Evaluation aborted.  
30 )