乐正

Actions speak louder than words.

Sicp-ex1-8

问题

求立方根的牛顿法基于如下事实,如果$y$是$x$的立方根的一个近似值,那么下式将给出一 个更好的近似值: $$ {\cfrac {x} {y^2} + 2y} \over 3 $$ 请利用这一公式实现一个类似平方根过程的求立方根过程。

解答

练习1.8 (ex1-8.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
;; Happy hacking Yuez - Emacs ♥ you!

(define (cbrt x)
  (define (good-enough? guess new-guess)
    (< (/ (abs (- guess new-guess)) guess) 0.0001))

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

  (define (cbrt-iter guess x)
    (if (good-enough? guess (improve guess x))
        (improve guess x)
        (cbrt-iter (improve guess x) x)))

  (cbrt-iter 1.0 x))

测试

1
2
3
4
5
6
7
8
(cbrt 27)
;Value: 3.0000000000000977

(cbrt 1)
;Value: 1.

(cbrt 8)
;Value: 2.000000000012062

draft

« sicp-ex1-7 sicp-ex1-9 »

Comments