Question 05

library(foreach)
library(doSNOW)
library(dplyr)

If d is the minimum distance between any pair of n uniformly distributed points from a unit square, then \(n(n-1)d^2\) ~ \(Exp(\frac{2}{\pi})\) provided that n is sufficiently large. Using R to check this result: First, write a function to produce n points uniformly distributed from the unit square. Then, write a function to calculate the smallest distance between any pair of n points. Change the value of n, perform simulation, and comment on what you find.

Function design

sim <- function(num){
  x <- runif(num) # 模擬num筆x座標
  y <- runif(num) # 模擬num筆y座標
  d = NULL
  while(length(x) > 1){
    a = (x[-1] - x[1])^2 
    b = (y[-1] - y[1])^2
    d = min(c(d,a+b)) 
    x <- x[-1]
    y <- y[-1]}
  return(d * num * (num - 1))}

使用分散式運算 開通道

cl<-makeCluster(3) #要開啟3個核心
registerDoSNOW(cl) #註冊後才真正開啟

Simulation 100 times

pv <- NULL
N = 100
for(j in 1:10){
sim2 <- foreach(i=1:1000,.combine = cbind,.export ="sim")%dopar%{sim(N)}
# ks.test 
f <- ks.test(sim2, "pexp",pi/2)
pv[j] <- f$p.value}
mean(pv)
## [1] 0.4621304
ex <- rexp(N,pi/2)
par(mfrow = c(1,2))
hist(sim2,main = "Simualtion Data")
hist(ex, main = "Data from Exponential(pi/2)")

Simulation 500 times

pv <- NULL
N = 500
for(j in 1:10){
sim2 <- foreach(i=1:1000,.combine = cbind,.export = "sim")%dopar%{sim(N)}
# ks.test 
f <- ks.test(sim2, "pexp",pi/2)
pv[j] <- f$p.value}
mean(pv)
## [1] 0.5381357
ex <- rexp(N,pi/2)
par(mfrow = c(1,2))
hist(sim2,main = "Simualtion Data")
hist(ex, main = "Data from Exponential(pi/2)")

Simulation 1000 times

pv <- NULL
N = 1000
for(j in 1:10){
sim2 <- foreach(i=1:1000,.combine = cbind,.export = "sim")%dopar%{sim(N)}
# ks.test 
f <- ks.test(sim2, "pexp",pi/2)
pv[j] <- f$p.value}
mean(pv)
## [1] 0.7126826
ex <- rexp(N,pi/2)
par(mfrow = c(1,2))
hist(sim2,main = "Simualtion Data")
hist(ex, main = "Data from Exponential(pi/2)")

關通道

stopCluster(cl)