This shows you the differences between two versions of the page.
|
exercise_1.31 [2009/03/02 00:58] mariorz |
exercise_1.31 [2009/03/02 01:02] (current) 204.14.159.185 |
||
|---|---|---|---|
| Line 11: | Line 11: | ||
| <code scheme> | <code scheme> | ||
| + | ; recursive | ||
| (define (product term a next b) | (define (product term a next b) | ||
| (if (> a b) | (if (> a b) | ||
| Line 17: | Line 17: | ||
| (* (term a) | (* (term a) | ||
| (product term (next a) next b)))) | (product term (next a) next b)))) | ||
| + | (product id 1 inc 6) | ||
| + | ; factorial | ||
| + | (define (factorial n) (product id 1 inc n)) | ||
| + | (factorial 6) | ||
| + | ; pi | ||
| + | (define (approximate-pi terms) | ||
| + | (define (term n) | ||
| + | (/ (if (even? n) (+ n 2) (+ n 3)) | ||
| + | (if (even? n) (+ n 3) (+ n 2)))) | ||
| + | (* 4 (product term 0 inc (- terms 1)))) | ||
| + | (approximate-pi 10) ; 524288/160083 = 3.275 | ||
| + | (approximate-pi 100) ; 3.1570301764551676 | ||
| - | |||
| - | (define (foo n) | ||
| - | (if (odd? n) | ||
| - | (- n 1) | ||
| - | n)) | ||
| - | |||
| - | (define (bar n) | ||
| - | (if (even? n) | ||
| - | (- n 1) | ||
| - | n)) | ||
| - | |||
| - | (define form-p | ||
| - | (* | ||
| - | (/ | ||
| - | (product foo 3 inc 100000) | ||
| - | (product bar 3 inc 100000)) | ||
| - | 4.0)) | ||
| Line 44: | Line 39: | ||
| B) | B) | ||
| <code scheme> | <code scheme> | ||
| + | ; iterative | ||
| (define (product term a next b) | (define (product term a next b) | ||
| (define (iter a result) | (define (iter a result) | ||
| (if (> a b) | (if (> a b) | ||
| result | result | ||
| - | (iter (next a) (* (term a) result)))) | + | (iter (next a) (* result (term a))))) |
| (iter a 1)) | (iter a 1)) | ||
| + | (product id 1 inc 6) | ||
| </code> | </code> | ||