23 hours ago
my attempt to do the exercises in sicp.
Tuesday, December 21, 2010
sicp exercise 3.64
;; Exercise 3.64. Write a procedure stream-limit that takes as arguments a stream and a number (the tolerance). It should examine the stream until it finds two successive elements that differ in absolute value by less than the tolerance, and return the second of the two elements. Using this, we could compute square roots up to a given tolerance by
;; (define (sqrt x tolerance)
;; (stream-limit (sqrt-stream x) tolerance))
(define (average x y)(/ (+ x y) 2))
(define (sqrt-improve guess x)
(average guess (/ x guess)))
(define (sqrt-stream x)
(define guesses
(cons-stream 1.0
(stream-map (lambda (guess)
(sqrt-improve guess x))
guesses)))
guesses)
(define (stream-limit stream tolerance)
(define (iter initial-value str)
(let ((s (stream-car str)))
(if (> tolerance (abs (- s initial-value))) s
(iter s (stream-cdr str)))))
(iter (stream-car stream) (stream-cdr stream)))
(define (sqrt x tolerance)
(stream-limit (sqrt-stream x) tolerance))
(newline)
(display (sqrt 30000 0.0000000000003))(newline)
;;Output:
;Loading "sicp_prob_03.64.scm"...
;173.20508075688772
;... done
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment