Skip to content

Instantly share code, notes, and snippets.

@tslumley
Created March 15, 2026 06:18
Show Gist options
  • Select an option

  • Save tslumley/578ef43b242d6125c26d394c22741fac to your computer and use it in GitHub Desktop.

Select an option

Save tslumley/578ef43b242d6125c26d394c22741fac to your computer and use it in GitHub Desktop.
Pi by coin tossing
one_pie<-function(N,n){
coins<-rbinom(n,1,.5)
means<- cumsum(coins)/(1:n)
if (any(means>0.5)) return(means[min(which(means>0.5))])
coins2<-c(coins,rbinom(N,1,.5))
means2<-cumsum(coins2)/(1:(N+n))
if (any(means2>0.5)) return(means2[min(which(means2>0.5))])
return((1/2)+(1/(N+n+1)))
}
> system.time(r<-replicate(100000,one_pie(1000,10)))
user system elapsed
1.072 0.046 1.115
> system.time(r<-replicate(100000,one_pie(1000,50)))
user system elapsed
0.761 0.040 0.800
> system.time(r<-replicate(100000,one_pie(1000,100)))
user system elapsed
0.838 0.050 0.887
##looks like n=50 is the sweet spot on my computer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment