欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

计算机程序的构造和解释 练习题3.5

程序员文章站 2022-03-03 19:05:56
#lang racket(define (estimate-pi trials) (sqrt (/ 6 (monte-carlo trials cesaro-test))))(define (cesaro-test) (= (gcd (rand) (rand)) 1))(define (monte-carlo trials experiment) (define (iter trials-remaining trials-passed) (cond ((= trials-rema...

矩形里面可以刚好包裹一个圆,直径就是长或者宽短的那一个,其实就是利用随机数,在矩形里面打点,概率就是圆形占矩形面积的比率,然后通过面积计算出圆周率。

#lang racket
(define (square x) (* x x))

(define (monte-carlo trials experiment)
  (define (iter trials-remaining trials-passed)
    (cond ((= trials-remaining 0)
           (/ trials-passed trials))
          ((experiment)
           (iter (- trials-remaining 1) (+ trials-passed 1)))
          (else
           (iter (- trials-remaining 1) trials-passed))))
  (iter trials 0))

(define (p x y r)
  (lambda (a b) (<= (+ (square (- a x)) (square (- b y))) (square r))))

(define (min a b)
  (if (> a b) b a))

(define (estimate-integral p x1 x2 y1 y2 trials)
  (define r (min (/ (- x1 x2) 2) (/ (- y1 y2) 2)))
  (define p? (p (/ (+ x1 x2) 2) (/ (+ y1 y2) 2) r))
  (define (test)
    (p? (random-in-range x1 x2) (random-in-range y1 y2)))
  (/ (* (- x1 x2) (- y1 y2) (monte-carlo trials test)) (square r)))
  
(define (random-in-range low high)
  (let ((range (- high low)))
    (+ low (random range))))

(estimate-integral p 2 8 4 10 1000)

运行结果,基本等于3.14

3 13/250

本文地址:https://blog.csdn.net/holybird0213/article/details/107307780