Blob


1 (define (search f neg-point pos-point)
2 (let ((midpoint (average neg-point pos-point)))
3 (if (close-enough? neg-point pos-point)
4 midpoint
5 (let ((test-value (f midpoint)))
6 (cond ((positive? test-value)
7 (search f neg-point midpoint))
8 ((negative? test-value)
9 (search f midpoint pos-point))
10 (else midpoint))))))
11 (define (close-enough? x y)
12 (< (abs (- x y)) 0.001))
14 (define (half-interval-method f a b)
15 (let ((a-value (f a))
16 (b-value (f b)))
17 (cond ((and (negative? a-value) (positive? b-value))
18 (search f a b))
19 ((and (negative? b-value) (positive? a-value))
20 (search f b a))
21 (else
22 (error "Values are not of opposite sign" a b)))))
23 (define tolerance 0.00001)
25 ;; Exercise 1.36. 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 x^x = 1000 by finding a fixed point of x-->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.)
27 (define (fixed-point f first-guess)
28 (define (close-enough? v1 v2)
29 (< (abs (- v1 v2)) tolerance))
30 (define (try guess)
31 (display guess)
32 (newline)
33 (let ((next (f guess)))
34 (if (close-enough? guess next)
35 (begin (display next)
36 next)
37 (try next))))
38 (newline)
39 (try first-guess))
41 (fixed-point (lambda (y) (+ (sin y) (cos y)))
42 1.0)
44 (define (sqrt x)
45 (fixed-point (lambda (y) (average y (/ x y)))
46 1.0))
48 (define (average x y)
49 (/ (+ x y) 2))
51 (define golden-ratio (fixed-point (lambda (x) (+ 1 (/ 1 x)))
52 1.0))
54 (define (test-case actual expected)
55 (load-option 'format)
56 (newline)
57 (format #t "Actual: ~A Expected: ~A" actual expected))
59 ;; (test-case golden-ratio (/ (+ 1.0 (sqrt 5.0)) 2.0))
61 ;; Then find a solution to x^x = 1000 by finding a fixed point of x-->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.)
63 (newline)
64 (newline)
65 (display "Finding solution to x^x = 1000 without average damping:")
66 (fixed-point (lambda (x) (/ (log 1000) (log x)))
67 2.0)
68 ;; 35 iterations
70 (newline)
71 (display "Finding solution to x^x = 1000 with average damping:")
72 (fixed-point (lambda (x) (average x (/ (log 1000) (log x))))
73 2.0)
74 ;; 10 iterations
76 ;; Average damping helps it converge much faster!