Friday, June 19, 2009

Ex-3.5

(define (random-in-range low high)
(let ((range (- high low)))
(+ low (random range))))
(define (estimate-integral p x1 x2 y1 y2 n)
(define (experiment)
(let ((x (random-in-range x1 x2))
(y (random-in-range y1 y2)))
(p x y)))
(* (monte-carlo n experiment) (* (- x2 x1) (- y2 y1))))

;procedure that creates a predicate to test whether
;given point lies in a circle
(define (make-in-circle-proc centreX centreY radius)
;for (x,y) to lie in the circle, distance
;between centre and (x,y) should be < radius
(lambda (x y)
(<= (+ (square (- centreX x))
(square (- centreY y)))
(square radius))))


;measuring PI by measuring area of unit circle
1 ]=> (exact->inexact
(estimate-integral
(make-in-circle-proc 0 0 1)
-1 1 -1 1 1000))
;Value: 3.032

1 ]=> (exact->inexact
(estimate-integral
(make-in-circle-proc 0 0 1)
-1 1 -1 1 1000))
;Value: 3.008

1 ]=> (exact->inexact
(estimate-integral
(make-in-circle-proc 0 0 1)
-1 1 -1 1 1000))
;Value: 2.964

1 ]=> (exact->inexact
(estimate-integral
(make-in-circle-proc 0 0 1)
-1 1 -1 1 1000))
;Value: 2.952

1 ]=> (exact->inexact
(estimate-integral
(make-in-circle-proc 0 0 1)
-1 1 -1 1 1000))
;Value: 3.036

1 ]=> (exact->inexact
(estimate-integral
(make-in-circle-proc 0 0 1)
-1 1 -1 1 1000))
;Value: 2.948

No comments:

Post a Comment