Skip to content

Instantly share code, notes, and snippets.

@gre
Last active August 29, 2015 14:22
Show Gist options
  • Save gre/6b7495791cd0220fe98e to your computer and use it in GitHub Desktop.
Save gre/6b7495791cd0220fe98e to your computer and use it in GitHub Desktop.
par(
mfrow=c(2,3),
mar=c(1,1,2,1),
mgp=c(1, 0.2, 0),
oma=c(0,0,2,0))
distributeCurve <- function (f, title, samples = 40000, drawSamples = 40) {
l <- c()
for (i in 0:samples) {
r <- f()
l <- c(l, r)
}
s <- c()
m <- 0
for (i in 0:drawSamples) {
l2 <- l[(i/drawSamples) < l]
l2 <- l2[l2 < ((i+1)/drawSamples)]
len <- length(l2)
s <- c(s, len)
m <- max(m, len)
}
random <- function (x) {
return (s[ceiling(x * drawSamples)])
}
curve(random, 0.01, 0.99, 50,
main=title,
ylim=c(0, 1.2 * m),
yaxt="n",
ylab="")
}
r <- function () {
return (runif(1))
}
distributeCurve(function () {
return (r());
}, "r()")
distributeCurve(function () {
return (r() * r())
}, "r() * r()")
distributeCurve(function () {
return (r() ^ 2)
}, "Math.pow(r(), 2)")
distributeCurve(function () {
return (r() + r())/2
}, "(r() + r())/2")
distributeCurve(function () {
return (0.3*r() + 0.7*r())
}, "0.3*r() + 0.7*r()")
distributeCurve(function () {
return (r() + r() + r())/3
}, "(r() + r() + r())/3")
title(
"different distribution of Math.random()",
outer=T)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment