Galton Box App

TizVic
2017-08-13

By w: Francis Galton [Public domain], via Wikimedia Commons

Motivation

The Galton Box App is a montecarlo simulator of a Galton Box machine.

The machine consists of a vertical board with interleaved rows of pins. Balls are dropped from the top, and bounce either left or right as they hit the pins.

If a ball bounces to the right k times on its way down (and to the left on the remaining pins) it ends up in the kth bin counting from the left.

Denoting the number of rows of pins in a bean machine by n, the number of paths to the kth bin on the bottom is given by the binomial coefficient \( {n \choose k} \).

If the probability of bouncing right on a pin is p (which equals 0.5 on an unbiased machine) the probability that the ball ends up in the kth bin equals:

\[ {n \choose k} p^k (1 − p)^{n−k} \]

Application

In this application (see code on GitHub)there is a possibility to vary some of the geometric parameters of the machine.

UI.R see code of ui.R on GitHub

The number of balls is the number of balls/beans that pass through the various layers.

The number of layers is the different layers of pins through which one must pass a ball.

The number of bins is the containers where the balls can finish.

Finally there is a parameter (Asimmetry coefficient) that serves to simulate real pin and balls that are not perfectly symmetrical.

Code embedded Sys.time() say that now is: 2017-08-13 23:54:13

Code explained

server.R see code of server.R on GitHub

The core of simulation is rbinom(). For every ball rbinom() simulates the passage of the ball through the number of pins layers established by the paramenter on the left panel.

input$realcoef is the parameter that affects the left/right simmetry.

# simulation with rbinom()
for (i in 1:input$balls) {
        m[i,] <- rbinom(input$layers, 1, .5 + input$realcoef)
}
# 1 go right, 0 go left so change 0 to -1 
m[m == 0] <- -1
# how may total steps left/right?
ss <- rowSums(m)

To calculate the net path made by the ball and then the bin where it ends, it is assigned +1 to right turn and -1 to left turn.

Code explained (...continued)

In the case that net path will be out of the box, is setted to the box limit.

Finally paths are converted to collector bins usin an histogram plot.

# if ball reach box limits, drop to extreme bins
ss[ss < -binStart] <- -binStart
ss[ss > binStart] <- binStart

# draw simulation
hist(ss+binStart, breaks = input$bins-1,
     xlab = "",
     main = paste("Simulation of Galton Box with",
                     input$layers,
                     "layers and",
                     input$balls,
                     "balls"))