Created
March 15, 2026 06:18
-
-
Save tslumley/578ef43b242d6125c26d394c22741fac to your computer and use it in GitHub Desktop.
Pi by coin tossing
This file contains hidden or 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
| 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))) | |
| } |
This file contains hidden or 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
| > 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