Skip to content

Instantly share code, notes, and snippets.

@jfacoustic
Last active October 17, 2020 15:37
Show Gist options
  • Save jfacoustic/efec04e30bfe2d7a23959ee37871f98c to your computer and use it in GitHub Desktop.
Save jfacoustic/efec04e30bfe2d7a23959ee37871f98c to your computer and use it in GitHub Desktop.
1.37, 1.38, 1.39 SICP
(define (cont-frac n d k)
(define (loop i k)
(if (= k i)
(/ (n i) (d i))
(/ (n i) (+ (d i) (loop (+ i 1) k)))))
(loop 1 k))
; 1.37
(define golden-ratio 1.61803398875)
(define (check-for-k f k uncertainty)
(let ((result (f (lambda (i) 1.0) (lambda (i) 1.0) k)))
(if (< (abs (- golden-ratio (/ 1.0 result))) uncertainty)
k
(check-for-k f (+ k 1) uncertainty))))
(check-for-k cont-frac 1 0.0001) ; so k=11 gives 0.0001 precision
(define (cont-frac-iterative n d k)
(define (iter i result)
(if (= i 0)
result
(iter (- i 1)
(/ (n i) (+ (d i) result)))))
(iter k (/ (n k) (d k))))
(/ 1.0 (cont-frac-iterative (lambda (i) 1.0) (lambda (i) 1.0) 1000))
(check-for-k cont-frac-iterative 1 0.000000001)
; 1.38
(define e (+ 2 (cont-frac (lambda (i) 1.0) (lambda (i)
(if (= 0 (remainder (+ i 1) 3))
(* (/ (+ i 1) 3) 2)
1))
100))) ; => 2.7182...
; 1.39
(define (tan-cf x k)
(let ((x2 (* x x -1)))
(cont-frac (lambda (i)
(if (= i 1) x x2))
(lambda (i) (let ((result (+ 1 (* (- i 1) 2))))
result))
k)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment