sicp-exercises/ex-1-37.rkt
2025-01-02 17:49:30 +03:00

42 lines
1.3 KiB
Racket

#lang racket
(define (cont-frac nf df k)
(define (recurse i)
(if (>= i k)
0
(/ (nf i) (+ (df i) (recurse (+ 1 i))))))
(recurse 0))
; produces the same result as cont-frac, but
; generates an iterative process.
(define (cont-frac-iterative nf df k)
(define (iterate i numer denom)
(if (<= i 0)
(/ numer denom)
(iterate (- i 1) (nf (- i 1)) (+ (df (- i 1)) (/ numer denom)))))
(iterate (- k 1) (nf k) (df k)))
(define (golden-ratio k)
"cont-frac generates 1/golden ratio, so we just inverse it to get the
real thing. call with k=1000 or something to get an accurate result"
(/ 1.0 (cont-frac-iterative (λ (i) 1.0) (λ (i) 1.0) k)))
;; example 1-38
(define (e-helper i)
(let ((r (remainder (- i 1) 3)))
(if (= 0 r)
(* 2.0 (/ (+ i 2) 3))
1.0)))
(define (eulers-constant k)
"Finds euler's constant. the continued fraction gives e - 2, so we add 2."
(+ 2 (cont-frac-iterative (λ (i) 1.0) e-helper k)))
;; example 1-39
(define (tan-cf x k)
"Finds an approximation of the tangent function. The first numerator is not negative,
even though our numerator function calculates them all as negative, so we need to negate
the result at the end."
(-
(cont-frac-iterative (λ (i) (- (if (<= i 0) x (* x x))))
(λ (i) (- (* 2 (+ i 1)) 1))
k)))