R语言蒙特卡罗估计π
初学蒙特卡洛
center <- c(2.5,2.5) #圓心 radius <- 2.5 #半徑 distancefromcenter <- function(a){ # 點到直线的距离 sqrt(sum((a-center)^2)) } n <- 1000000 A <- matrix(runif(2*n,0,5),nrow = n,byrow = T) #一行为一个点,n行 b <- apply(A, 1, distancefromcenter) #对矩阵A按行计算点到直线的距离 num <- mean(b<radius) #括号里为1或0,求均数相当于计算了1占n的比例 table(b<radius) pai <- num*4 #圆面积与正方形面积之比 为π/4 pai #画图 par(bg=‘beige‘) #背景色 plot(A,col=‘azure3‘,xlab = ‘‘,ylab = ‘‘,asp = 1) #asp让x和y轴的刻度量度一样 abline(h=0,col=‘goldenrod4‘,lty=‘dotdash‘,lwd=3) #画上下左右的直线 abline(h=5,col=‘goldenrod4‘,lty=‘dotdash‘,lwd=3) abline(v=5,col=‘goldenrod4‘,lty=‘dotdash‘,lwd=3) abline(v=0,col=‘goldenrod4‘,lty=‘dotdash‘,lwd=3) points(A[b<radius,],col=‘aquamarine3‘) install.packages(‘plotrix‘) library(plotrix) draw.circle(2.5,2.5,2.5,border=‘coral2‘,lty=‘dashed‘,lwd=3) #画圆 points(2.5,2.5,col=‘brown1‘,pch=19,cex=1.5,lwd=1.5) #圆心 #模拟 paivector <- c() for(i in 1:10000){ n <- i A <- matrix(runif(2*n,0,5),nrow = n,byrow = T) #一行为一个点,n行 b <- apply(A, 1, distancefromcenter) d <- subset(b,b<radius) num <- length(d)/length(b) paivector[i] <- num*4 } install.packages(‘data.table‘) library(data.table) class(paivector) pa <- data.frame(paivector) pa1 <- data.table(pa) #enhanced data frame pai <- pa1[,id:=seq(0,9999)] #可以直接加添加一列,但是pa不行 pai <- pa1[,error := abs(pi-paivector)] names(pai) <- c(‘guess‘,‘id‘,‘error‘) library(ggplot2) ggplot(pai,aes(x=id,y=error))+geom_line(color=‘#388E8E‘)+ggtitle(‘error‘)+xlab(‘sample size‘)+ylab(‘error‘)
相关推荐
zhjn0 2020-11-24
夜斗不是神 2020-11-17
学习web前端 2020-11-09
waiwaiLILI 2020-11-03
raidtest 2020-10-09
myccc 2020-09-24
jzlixiao 2020-09-15
guicaizhou 2020-09-15
digwtx 2020-09-14
大秦铁骑 2020-08-19
thatway 2020-08-19
lovecodeblog 2020-08-19
codetyper 2020-08-16
comwayLi 2020-08-16
MongoDB数据库 2020-08-16
cjsyrwt 2020-08-14
Tristahong 2020-08-05
csuzxm000 2020-08-02
前端开发Kingcean 2020-07-30