Construction and interpretation exercises computer program 1.37

The following conversion formula may be obtained from the subject:
x k = > N k D k x k 1 = > N k 1 D k 1 + x k . . . . . . . x 2 = > N 2 D 2 + x 3 x 1 = > N 1 D 1 + x 2 x_k=> \frac{N_k}{D_{k}}\\ x_{k-1}=> \frac{N_{k-1}}{D_{k-1}+x_k}\\ .......\\ x_{2}=> \frac{N_2}{D_2+x_{3}}\\ x_{1}=> \frac{N_1}{D_1+x_{2}}
You may then be converted to give the formula
x = > N D + x x => \frac{N}{D+x}
The most common iteration is from 1 to k, this is from 1 to k, somewhat difficult to understand, we see the final process

#lang racket
//线性递归
(define (cont-frac n d k)
  (define (recursion a)
  (if (= a k) (/ (n a) (d a))
      (/ (n a) (+ (d a) (recursion (+ a 1))))))
  (recursion 1)
)
//线性迭代
(define (cont-frac-iter n d k)
  (define (iter a result)
    (if (= a 1) result
        (iter (- a 1) (/ (n k) (+ (d k) result)))))
  (iter k (/ (n k) (d k)))
 )

(define (golden-section k)
  (cont-frac (lambda (i) 1.0)
           (lambda (i) 1.0)
           k))
//辅助的输出过程
(define (find-point n)
  (define (iter k)
    (display "k:")
    (display k) 
    (display " value:")
    (display (golden-section k))
    (newline)
    (if (= k n)
        0
        (iter (+ k 1))))
  (iter 1)
)

(find-point 20)

operation result

k:1 value:1.0
k:2 value:0.5
k:3 value:0.6666666666666666
k:4 value:0.6000000000000001
k:5 value:0.625
k:6 value:0.6153846153846154
k:7 value:0.6190476190476191
k:8 value:0.6176470588235294
k:9 value:0.6181818181818182
k:10 value:0.6179775280898876
k:11 value:0.6180555555555556
k:12 value:0.6180257510729613
k:13 value:0.6180371352785146
k:14 value:0.6180327868852459
k:15 value:0.6180344478216819
k:16 value:0.6180338134001252
k:17 value:0.6180340557275542
k:18 value:0.6180339631667065
k:19 value:0.6180339985218034
k:20 value:0.6180339850173579

k = 11 when four decimal precision.

Published 27 original articles · won praise 1 · views 467

Guess you like

Origin blog.csdn.net/holybird0213/article/details/104861327