Complete up to 3.82

This commit is contained in:
Oliver Payne 2023-02-16 14:58:06 +00:00
parent c695e46745
commit e67c115317
1 changed files with 47 additions and 0 deletions

View File

@ -836,4 +836,51 @@
rand)
;; Test with (define req (make-stream '(generate generate (reset 19) generate)))
;; 3.82
;; Accumulate stream to give a running total
(define (stream-acc input)
(define acc
(cons-stream (stream-car input)
(add-streams acc
(stream-cdr input))))
acc)
;; Scale stream of random numbers to lie in [low,high]
(define (random-stream-in-range low high)
(define ones (cons-stream 1 ones))
(define (random-stream)
(cons-stream (random (- high low))
(random-stream)))
(add-streams (scale-stream ones low)
(random-stream)))
;; A procedure that generates a stream of booleans:
;; Does a random element from [-1,1]x[-1,1] lie in the cirle
;; of radius 1 centred at (0, 0).
;; P(in circle) = pi*1^2 / 4 = pi/4
(define in-circle-test
(lambda ()
(define (in-circle? radius)
(lambda (x y)
(<= (+ (* x x) (* y y))
(* radius radius))))
(let ((radius 1)
(x (random-stream-in-range -1.0 1.0))
(y (random-stream-in-range -1.0 1.0)))
(stream-map (in-circle? radius) x y))))
(define (monte-carlo experiment-stream)
(define num-trials integers)
(define num-trials-passed
(stream-acc (stream-map (lambda (x) (if x 1 0)) experiment-stream)))
(div-streams num-trials-passed num-trials))
;; Area of circle is pi/r^2. Area of square is 2*2 = 4
;; So calculated probability is pi/4.
(define estimate-pi
(scale-stream (monte-carlo (in-circle-test)) 4.0))
)