SICP-2nd-Edition-Exercise-1.36

From Boozled

Revision as of 22:25, 20 December 2008 by Harry (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

Contents

Exercise 1.31 From SICP

Details from SICP are here

Modify fixed-point so that it prints the sequence of approximations it generates, using the newline and display primitives shown in exercise 1.22. Then find a solution to xx = 1000 by finding a fixed point of x = \frac{log(1000)}{log(x)}. (Use Scheme's primitive log procedure, which computes natural logarithms.) Compare the number of steps this takes with and without average damping. (Note that you cannot start fixed-point with a guess of 1, as this would cause division by log(1) = 0.)

Attempt

The damped method requires less steps.

Scheme

  1. (define tolerance 0.00001)
  2. (define (fixed-point f first-guess)
  3.   (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance))
  4.   (define (try guess)   
  5.     (display guess)
  6.     (newline)
  7.     (let ((next (f guess)))
  8.       (if (close-enough? guess next)
  9.           next
  10.           (try next))))
  11.   (try first-guess))
  12.  
  13. (define (phi x) (+ 1 (/ 1 x)))
  14. (define (xsquared x) (/ (log 1000) (log x)))
  15.  
  16. (define (hxsquared x) (/ (+ x (/ (log 1000) (log x))) 2))
  17.  
  18. (define (xy x) (/ x y))
  19.  
  20. (define (sqroot x)
  21.   (fixed-point (lambda (y) (/ x y)) 
  22.                1.0))
  23.  
  24. (display (fixed-point xsquared 1.1))
  25. (newline)
  26. (newline)
  27. (display (fixed-point hxsquared 1.1))

Parent Course

6.001_Structure_and_Interpretation_of_Computer_Programs

Further Reading