Monte Carlo methods are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. One of the basic examples of getting started with the Monte Carlo algorithm is the estimation of Pi.
The idea is to simulate random (x, y) points in a 2-D plane with domain as a square of side 2r units centered on (0,0). Imagine a circle inside the same domain with same radius r and inscribed into the square. Here a R script estimates the value of π using the Monte Carlo method in R and visualize the results with a plot.
The idea is to simulate random (x, y) points in a 2-D plane with domain as a square of side 2r units centered on (0,0). Imagine a circle inside the same domain with same radius r and inscribed into the square. Here a R script estimates the value of π using the Monte Carlo method in R and visualize the results with a plot.
Code:
# Set the number of random pointsnum_points <- 10000# Generate random (x, y) pointsx <- runif(num_points, min = -1, max = 1)y <- runif(num_points, min = -1, max = 1)# Check if points are inside the unit circleinside_circle <- x^2 + y^2 <= 1# Estimate πpi_estimate <- sum(inside_circle) / num_points * 4cat("Estimated value of π:", pi_estimate, "\n")# Plot the pointsplot(x, y, col = ifelse(inside_circle, "blue", "red"), pch = 16, cex = 0.6, xlab = "x", ylab = "y", main = paste("Monte Carlo Simulation to Estimate π\nEstimated π =", round(pi_estimate, 5)))# Add a unit circle for referencesymbols(0, 0, circles = 1, inches = FALSE, add = TRUE, fg = "black")
Statistics: Posted by geev03 — Wed Dec 04, 2024 9:08 am — Replies 2 — Views 64