Model: Code Interpreter
ALPHA
Write some R code that creates something that somebody who runs it would find interesting and / or surprising
Sure! Here's a simple R code that uses Monte Carlo simulation to approximate the value of pi. The code creates an animation of points being plotted inside a square with a quarter circle inscribed in it. The ratio of points inside the circle to the total points gives an estimate of pi. Users who run this code will find it interesting to see the points being plotted in real-time, and they may be surprised by how close the approximation gets to the actual value of pi.
RCopy codelibrary(gganimate)
# Number of points to be generated for simulation
n_points <- 1000
# Create a data frame to store the coordinates and status (inside/outside circle) of points
df <- data.frame(x = double(), y = double(), status = character())
# Initialize a ggplot object with axis limits
p <- ggplot() + xlim(0, 1) + ylim(0, 1)
# Create an animation
anim <- p + transition_states(states = seq_len(n_points),
transition_length = 0,
state_length = 0.1)
# Loop to generate points and update the data frame
for (i in seq_len(n_points)) {
x <- runif(1) # Random x-coordinate
y <- runif(1) # Random y-coordinate
# Check if the point is inside the quarter circle (radius = 1)
if (x^2 + y^2 <= 1) {
status <- "inside"
} else {
status <- "outside"
}
# Append the point to the data frame
df <- rbind(df, data.frame(x = x, y = y, status = status))
# Update the animation with the new point
anim <- anim + geom_point(data = df, aes(x = x, y = y, color = status), size = 2)
}
# Estimate the value of pi
pi_estimate <- 4 * nrow(df[df$status == "inside", ]) / n_points
print(paste("Estimated value of pi:", pi_estimate))
# Animate the plot
animate(anim, nframes = n_points, fps =