Last active
November 28, 2016 17:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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