learning-sicp

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

exercise-7.scm (1672B)


      1 (define-library (sicp solutions chapter-1 exercise-7)
      2   (import (scheme base))
      3   (import (scheme write))
      4   (export square-root)
      5 
      6   (begin
      7     #!
      8 
      9     *Exercise 1.7:* The `good-enough?' test used in computing square
     10     roots will not be very effective for finding the square roots of
     11     very small numbers.  Also, in real computers, arithmetic operations
     12     are almost always performed with limited precision.  This makes
     13     our test inadequate for very large numbers.  Explain these
     14     statements, with examples showing how the test fails for small and
     15     large numbers.  An alternative strategy for implementing
     16     `good-enough?' is to watch how `guess' changes from one iteration
     17     to the next and to stop when the change is a very small fraction
     18     of the guess.  Design a square-root procedure that uses this kind
     19     of end test.  Does this work better for small and large numbers?
     20 
     21     !#
     22 
     23     ;; TODO: The wordy parts.
     24 
     25     (define (square-root x)
     26       (define (average a b)
     27         (/ (+ a b) 2))
     28 
     29       (define (improve guess x)
     30         ;; (dp guess x)
     31         (average guess (/ x guess)))
     32 
     33       (define (good-enough? old-guess new-guess)
     34         (define bound 0.0000000000001)
     35         (define ratio (/ old-guess new-guess))
     36 
     37         (define within-bounds
     38           (< (- 1 bound) ratio (+ 1 bound)))
     39 
     40         ;; (dp bound ratio within-bounds)
     41 
     42         within-bounds)
     43 
     44       (define (square-root-iter guess x)
     45         (define new-guess (improve guess x))
     46         ;; (dp new-guess)
     47 
     48         (if (good-enough? guess new-guess)
     49             guess
     50             (square-root-iter new-guess
     51                               x)))
     52 
     53       (square-root-iter 1 x))))