SICP 1.3 exercises

1.29

(define (simpson f a b n)
  (define h (h-func a b n))
  (define (yk k) (f (+ a (* k h))))
  (define (g x)
    (cond ((or (= 0 x) (= x n)) (yk x))
          ((even? x) (* 2 (yk x)))
          (else (* 4 (yk x)))))
  (/ (* h
      (sum g 0 inc n)) 3))

(integral cube 0 1 0.01)
0.2499875

(simpson cube 0 1 100.0)
0.25

(integral cube 0 1 0.001)
0.249999875000001

(simpson cube 0 1 1000.0)
0.25

I think guile does some kind of optimization. I also had to increase the stack limit. This exercise was mindbending to start with, but some concentrated thinking eventually yielded a working answer.

1.30

(define (sum-2 term a next b)
  (define (iter a result)
    (if (> a b)
        result
      (iter (next a) (+ (term a) result))))
  (iter a 0))

This was pretty straightforward.

Comments: A head start into 1.3! 1.2 was valuable in the way it makes you think about processes. This chapter seems to be more fun though.

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s