PasteRack.org
Paste # 60859
2016-10-21 01:18:12

Fork as a new paste.

Paste viewed 69 times.


Embed:

  1. #lang racket
  2.  
  3. (define (estimate-pi trials)
  4.         (define (cesaro-test)
  5.                 (= (gcd (random 4294967087) (random 4294967087)) 1))
  6.         (sqrt (/ 6 (monte-carlo trials cesaro-test))))
  7. (define (monte-carlo trials experiment)
  8.         (define (iter trials-remaining trials-passed)
  9.                 (cond ((= trials-remaining 0)
  10.                                         (/ trials-passed trials))
  11.                                         ((experiment)
  12.                                                 (iter (- trials-remaining 1)
  13.                                                                         (+ trials-passed 1)))
  14.                                         (else
  15.                                                 (iter (- trials-remaining 1)
  16.                                                                         trials-passed))))
  17. (iter trials 0))
  18. ;------------------------------------------
  19. ;exercise 3-5
  20. (define (estimate-integral P x1 x2 y1 y2 trials)
  21.         (define (experiment)
  22.                         (P (random x1 (+ x2 1))
  23.                                 (random y1 (+ y2 1))))
  24.         ; (* area (monte-carlo trials experiment)) area * portion
  25.         (exact->inexact (* (* (abs (- x2 x1)) (abs (- y2 y1)))
  26.                 (monte-carlo trials experiment))))
  27.  
  28. ; the region is described by P(x, y) that is true for p(x,y) in the region and false otherwise.
  29. ; problem here
  30. (define (make-circle-predicate a b r)
  31.         ;make a predicate such as (x-a)^2 + (y-b)^2 <= r^2
  32.         ; return lambda (x y) according to above formula
  33.         (lambda (x y)
  34.                 (<= (+ (sqr (- x a)) (sqr (- y b)))
  35.                                 (sqr r))))
  36.  
  37. (define c1 (make-circle-predicate 4 4 1))
  38. (estimate-integral c1 3 5 3 5 100000)

=>

2.23176