2015/10/08

SICP 問題1.37

無限連分数の近似値

;; 再帰的プロセス
(define (cont-frac n d k)
  (define (recur i)
    (if (= i k)
        (/ (n i) (d i))
        (/ (n i) (+ (d i) (recur (+ i 1))))))
  (recur 1))

;; 反復的プロセス
(define (cont-frac n d k)
  (define (iter i res)
    (if (= i 0)
        res
        (iter (- i 1) (/ (n i) (+ (d i) res)))))
  (iter (- k 1) (/ (n k) (d k))))
gosh> 
1 -> 1.0
2 -> 0.5
3 -> 0.6666666666666666
4 -> 0.6000000000000001
5 -> 0.625
6 -> 0.6153846153846154
7 -> 0.6190476190476191
8 -> 0.6176470588235294
9 -> 0.6181818181818182
10 -> 0.6179775280898876
11 -> 0.6180555555555556
12 -> 0.6180257510729613
13 -> 0.6180371352785146
14 -> 0.6180327868852459
15 -> 0.6180344478216819
16 -> 0.6180338134001252
17 -> 0.6180340557275542
18 -> 0.6180339631667064
19 -> 0.6180339985218034
20 -> 0.6180339850173578

k = 11以上で有効桁数4桁となる.


© 2022 wat-aro