scheme牛顿迭代

  • 求平方根
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
(define (square x) (* x x))

(square 2)

(define (abs x)
(if (< x 0) (- x) x)
)

(abs -1)

;;(define (goodenough guess x)
;; (< (abs (- (square guess) x)) 0.0001))

(define (goodenough guess x)
(< (abs (- (/ guess (average guess (/ x guess))) 1)) 0.01))

(goodenough 3 9)

(define (average a b)
(/ (+ a b) 2))

(average 9 3)

(define (sqrt-iter guess x)
(if (goodenough guess x) guess (sqrt-iter (average guess (/ x guess)) x))
)

(sqrt-iter 1.0 9)

(define (sqrt x) (sqrt-iter 1.0 x))

(sqrt 9)
  • 求立方根
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(define (square x) (* x x))

(square 2)

(define (cube x) (* x x x))

(cubert 2)

(define (abs x)
(if (< x 0) (- x) x)
)

(abs -1)
(abs 1)

(define (goodenough guess x)
(< (abs (- (/ guess (improve guess x)) 1)) 0.01))

(goodenough 3 9)

(define (improve guess x)
(/ (+ (/ x (square guess)) (* 2 guess)) 3))

(improve 1.0 9)

(define (average a b)
(/ (+ a b) 2))

(average 9 3)

(define (cubert-iter guess x)
(if (goodenough guess x) guess (cubert-iter (improve guess x) x))
)

(cubert-iter 2.0 27)

(define (cubert x) (cubert-iter 1.0 x))

(cubert 27)

推荐一首好听个歌给大家,希望大家都能成为自己的Best Of Me