learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-8.scm (1443B)


      1 (define-library (sicp solutions chapter-1 exercise-8)
      2   (import (scheme base))
      3   (export cube-root)
      4 
      5   (begin
      6     #!
      7 
      8     *Exercise 1.8:* Newton's method for cube roots is based on the
      9     fact that if y is an approximation to the cube root of x, then a
     10     better approximation is given by the value
     11 
     12     x/y^2 + 2y
     13     ----------
     14     3
     15 
     16     Use this formula to implement a cube-root procedure analogous to
     17     the square-root procedure.  (In section *Note 1-3-4:: we will see
     18                                     how to implement Newton's method in general as an abstraction of
     19                                     these square-root and cube-root procedures.)
     20 
     21     !#
     22 
     23     (define (cube-root x)
     24       (define (improve guess)
     25         (/ (+ (/ x
     26                  (* guess guess))
     27               (* 2 guess))
     28            3))
     29 
     30       (define (good-enough? old-guess new-guess)
     31         (define bound 0.0000000000001)
     32         (define ratio (/ old-guess new-guess))
     33 
     34         (define within-bounds
     35           (< (- 1 bound) ratio (+ 1 bound)))
     36 
     37         within-bounds)
     38 
     39       (define (cube-root-iter guess)
     40         (define new-guess (improve guess))
     41         (if (good-enough? guess new-guess)
     42             guess
     43             (cube-root-iter new-guess)))
     44 
     45       ;; Start with a floating point 1.0 instead of an integer 1 to
     46       ;; avoid creating a rational with huge enumerator and
     47       ;; denominator with the "/" procedure.
     48       (cube-root-iter 1.0))))