Differences

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>
 
exercise_1.31.txt · Last modified: 2009/03/02 01:02 by 204.14.159.185
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki