読者です 読者をやめる 読者になる 読者になる

SICPゼミ第32回

練習問題3.81
(define (rand-stream stream)
  (define (rand-stream-iter stream mt)
    (if (stream-null? stream)
        the-empty-stream
        (let ((message (stream-car stream)))
          (if (eq? message 'generate)
              (cons-stream (mt-random-integer mt 1000) (rand-stream-iter (stream-cdr stream) mt))
              (let ((new-mt (make <mersenne-twister> :seed message)))
                (cons-stream (mt-random-integer new-mt 1000) (rand-stream-iter (stream-cdr stream) new-mt)))))))
  (rand-stream-iter stream (make <mersenne-twister> :seed (sys-time))))
(define (rand-stream stream)
  (define (rand-stream-iter stream last)
    (if (stream-null? stream)
        the-empty-stream
        (let ((message (stream-car stream)))
          (if (eq? message 'generate)
              (let ((new-num (rand-update last)))
                (cons-stream new-num (rand-stream-iter (stream-cdr stream) new-num)))
              (cons-stream message (rand-stream-iter (stream-cdr stream) message))))))
  (rand-stream-iter stream (rand)))

by pine

練習問題3.82

racket だと (random) で 0~1 の乱数が出てくるので(0,0), (1,1) の長方形でやりました。

(define (estimate-integral P x1 x2 y1 y2)
  (define (estimate-integral-iter passed failed)
    (define (guessed-value passed failed)
      (let ((rectangle-area (* (- x2 x1) (- y2 y1))))
        (* 4 (* rectangle-area (/ (* passed 1.0) (+ passed failed))))))
    (define (next passed failed)
      (cons-stream
       (guessed-value passed failed)
       (estimate-integral-iter passed failed)))
    (let ((x (random))
          (y (random)))
      (if (P x y)
          (next (+ passed 1) failed)
          (next passed (+ failed 1)))))
  (estimate-integral-iter 0 0))
(define (P x y)
    (< (+ (* (- x 0.5) (- x 0.5)) (* (- y 0.5) (- y 0.5))) 0.25))

実行結果
f:id:sicp-zemi:20161130193143p:plain



by tube