查看原文
其他

使用蒙特-卡罗方法来估计Pi

Y叔叔 YuLabSMU 2022-09-20
在《利用多边形估计Pi值》一文中介绍了使用多边形,通过数值方法,来估计Pi值,今天介绍一个使用抽样的方法。

圆和外接正方形的面积比,是

通过这一比值,可以使用蒙特-卡罗方法来估计Pi,这是Monte Carlo方法的最经典的一个例子。

getPI <- function(N) {
    x <- runif(N)
    y <- runif(N)
    hits <- sum(sqrt(x^2+y^2) < 1)
    pi <- 4*hits/N
    return(pi)
}
options(digits=15)
set.seed(12345)
n <- c(seq(from=100, to=1000, by=100),
       seq(from=1000, to=10000, by=1000)
       )

require(ggplot2)
p <- ggplot() +
    aes(x=n, y=sapply(n, getPI)) +
    geom_point() +
    geom_hline(aes(yintercept=pi, colour="red")) +
    xlab("")+ ylab("") +
    theme(legend.position="none")

print(p)

往期精彩

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存