my attempt to do the exercises in sicp.

Tuesday, December 21, 2010

sicp exercise 3.62

;; Exercise 3.62.  Use the results of exercises 3.60 and 3.61 to define a procedure div-series that divides two power series. Div-series should work for any two series, provided that the denominator series begins with a nonzero constant term. (If the denominator has a zero constant term, then div-series should signal an error.) Show how to use div-series together with the result of exercise 3.59 to generate the power series for tangent.

(define (integrate-series s)
  (define (integrate-series-i s n)
    (cons-stream  (/ (stream-car s) n)
                  (integrate-series-i (stream-cdr s) (+ 1 n))))
  (integrate-series-i s 1))

(define (mul-stream s1 s2)
  (stream-map * s1 s2))

(define minus-one
  (cons-stream -1 minus-one))

(define (scale-stream stream factor)
  (stream-map (lambda (x) (* x factor)) stream))

(define (add-streams s1 s2)
  (cons-stream (+ (stream-car s1) (stream-car s2))
               (add-streams (stream-cdr s1)(stream-cdr s2))))

(define (mul-series s1 s2)
    (* (stream-car s1)
       (stream-car s2))
       (add-streams (scale-stream (stream-cdr s1) (stream-car s2))
                    (scale-stream (stream-cdr s2) (stream-car s1)))
       (cons-stream 0 (mul-series (stream-cdr s1) (stream-cdr s2))))))

(define (invert-unit-series s)
  (define X
    (cons-stream 1 (mul-stream minus-one (mul-series (stream-cdr s) X))))

(define (div-series s1 s2)
  (if (= 0 (stream-car s2)) 'Error
      (mul-series s1 (invert-unit-series s2))))

(define cosine-series
  (cons-stream 1 (mul-stream minus-one (integrate-series sine-series))))

(define sine-series
  (cons-stream 0 (integrate-series cosine-series)))

(define tangent-series (div-series sine-series cosine-series))

(display (stream-ref tangent-series 0))(newline)
(display (stream-ref tangent-series 1))(newline)
(display (stream-ref tangent-series 2))(newline)
(display (stream-ref tangent-series 3))(newline)
(display (stream-ref tangent-series 4))(newline)
(display (stream-ref tangent-series 5))(newline)
(display (stream-ref tangent-series 6))(newline)
(display (stream-ref tangent-series 7))(newline)
(display (stream-ref tangent-series 8))(newline)
(display (stream-ref tangent-series 9))(newline)
(display (stream-ref tangent-series 10))(newline)
(display (stream-ref tangent-series 11))(newline)

;; Output
;Loading "sicp_prob_03.62.scm"...
;... done

No comments: