- 1
- Import the Random module for generating random numbers
- 2
- Import the Distributed module for parallel computing capabilities
- 3
- Set a specific random seed for reproducibility
TaskLocalRNG()
Reneder Report Link: estimating pi through monte carlo simualtion
Implement a Monte Carlo simulation based on Buffon’s needle problem to estimate the value of \(\pi\). Buffon’s needle is a classic problem in probability theory that relates the probability of a needle crossing parallel lines on a plane to the value of \(\pi\).
Understanding the problem (Polya 2014):
\[ \pi \approx \frac{2 * needle\_length * number\_of\_tosses}{line\_spacing * number\_of\_crosses} \]
Stepwise implementation of the Problem in Julia code.
TaskLocalRNG()
```{julia}
"""
toss_needle(d::Float64)
Generate a random point inside a semicircle with radius `d/2`.
Returns:
- A tuple `(x, θ)` where `x` is the distance from the center of the needle to the nearest line,
and `θ` is the angle of the needle with the horizontal.
"""
function toss_needle(d::Float64)
1 x = rand() * d / 2
2 θ = rand() * π
return x, θ
end
```Main.Notebook.toss_needle
```{julia}
"""
cross_line(x::Float64, θ::Float64, L::Float64)
Check if a point `(x, θ)` crosses a line parallel to the x-axis with a distance `L/2` from the center.
Returns:
- `true` if the needle crosses the line, otherwise `false`.
"""
function cross_line(x::Float64, θ::Float64, L::Float64)
1 return x <= (L / 2) * sin(θ)
end
```Main.Notebook.cross_line
```{julia}
"""
estimate_pi_par(nb_tosses::Int64, L::Float64, d::Float64)
Estimate π using Buffon's Needle method.
Args:
- `nb_tosses`: The number of random tosses to perform.
- `L`: The length of the needle.
- `d`: The distance between the lines.
Returns:
- An estimate of π based on the number of times the needle crosses a line.
"""
function estimate_pi_par(nb_tosses::Int64, L::Float64, d::Float64)
1 nb_crosses = @distributed (+) for _ in 1:nb_tosses
2 x, θ = toss_needle(d)
3 cross_line(x, θ, L) ? 1 : 0
end
4 return (2 * L * nb_tosses) / (d * nb_crosses)
end
```Main.Notebook.estimate_pi_par
```{julia}
# Parameters
L = 1.0 # Length of the needle
d = 2.0 # Distance between the lines
nb_tosses = 1_000_000 # Number of tosses
```1000000
```{julia}
# Estimate π
π_estimate = estimate_pi_par(nb_tosses, L, d)
println("Estimated π: $π_estimate")
```Estimated π: 3.1328320802005014