weima learns to program

my attempt to do the exercises in sicp.

Tuesday, December 21, 2010

sicp exercise 3.61

;;Exercise 3.61.  Let S be a power series (exercise 3.59) whose constant term is 1. Suppose we want to find the power series 1/S, that is, the series X such that S Â· X = 1. Write S = 1 + SR where SR is the part of S after the constant term. Then we can solve for X as follows:

;;In other words, X is the power series whose constant term is 1 and whose higher-order terms are given by the negative of SR times X. Use this idea to write a procedure invert-unit-series that computes 1/S for a power series S with constant term 1. You will need to use mul-series from exercise 3.60.

(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)
(cons-stream
(* (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))))
X)

(define exp-series
(cons-stream 1 (integrate-series exp-series)))

(define inverse-exp-series (invert-unit-series exp-series))

;; Testing:
;; computing series expansion of 1/e^x. which is equal to e^-x
;; so the result should be same as e^x but with alternate signs
(newline)
(display (stream-ref inverse-exp-series 0))(newline)
(display (stream-ref inverse-exp-series 1))(newline)
(display (stream-ref inverse-exp-series 2))(newline)
(display (stream-ref inverse-exp-series 3))(newline)
(display (stream-ref inverse-exp-series 4))(newline)
(display (stream-ref inverse-exp-series 5))(newline)
(display (stream-ref inverse-exp-series 6))(newline)
(display (stream-ref inverse-exp-series 7))(newline)
(display (stream-ref inverse-exp-series 8))(newline)

;; Output:
;1
;-1
;1/2
;-1/6
;1/24
;-1/120
;1/720
;-1/5040
;1/40320
;... done

; Indeed it is.....