# CONFIGURATION --------------------------------------------------------------- RATIO = 0.75 # Ratio of needle length to line spacing. SAMPLES = 500000 # Number of times that the needle is dropped. SEED = 13 # Random seed for repeatability. # ----------------------------------------------------------------------------- buffon <- function() { # Sample angle of needle with respect to lines. # theta = runif(1, 0, pi / 2) # # Sample the location of the needle's centre. Does the needle cross a line? # runif(1) <= RATIO * sin(theta) } set.seed(SEED) cross = replicate(SAMPLES, buffon()) # # Estimate pi. # cat(sprintf("ratio = %.3f / %6d samples -> estimate = %.6f\n", RATIO, SAMPLES, 2 * SAMPLES * RATIO / sum(cross)))