Skip to content

Instantly share code, notes, and snippets.

@mbeltagy
Last active November 28, 2016 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbeltagy/ace0208820559ded22e7867a140400af to your computer and use it in GitHub Desktop.
Save mbeltagy/ace0208820559ded22e7867a140400af to your computer and use it in GitHub Desktop.
Similar to the parksim in the R probability book, but 10 times faster
using Distributions
# Fast, but too compact
function parksim_fast(nreps)
gd=Geometric(0.15)
mean(begin x=rand(gd)+1; x<=10? 11-x:x-11 end for i=1:nreps)
end
# A litte longe but clearer
function parksim_fast2(nreps)
gd=Geometric(0.15)
function f()
x=rand(gd)+1
x<=10? 11-x:x-11
end
mean(f() for i=1:nreps)
end
# R like function
function parksim(nreps)
gd=Geometric(0.15)
nval=rand(gd,nreps)+1
dvals=map(x->x<=10? 11-x:x-11,nval)
mean(dvals)
end
# Testing the times
# Warm up
parksim_fast2(10)
parksim_fast(10)
parksim(10)
@time parksim_fast2(1000_000_00)
@time parksim_fast(1000_000_00)
@time parksim(1000_000_00)
parksim <-function(nreps) {
nvals<-rgeom(nreps,0.15)+1
dvals<-ifelse(nvals<=10,11-nvals,nvals-11)
mean(dvals)
}
system.time(parksim(100000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment