Using the Sobol-Sequence to calculate pi in Julia

Viewed 106

One can approximate pi by looking at the relationship of randomly generated points on a sqaure with a circle inside.

enter image description here

function picircle(n)
n = n
N = 2n+1

x = range(-1, 1, length=N)
y = rand(N)

center = (0,0)
radius = 1

n_in_circle = 0

for i in 1:N
    if norm((x[i], y[i]) .- center) < radius
        n_in_circle += 1
    end
end

println(4 * n_in_circle / N)
end
picircle(1000)
3.1424287856071964

However, I would like to use the Quasi-Monte Carlo method. Instead of using pseudo random numbers I want to use numbers from a Sobol-Sequence. I know how to generate them but I am not sure how to implement it in my code.

using Sobol
s = SobolSeq(2) # Creates a Sobol-Sequenz in 2 Dimensions
1 Answers

See the README.md of Sobol.jl to learn how to iterate over a SobolSeq. The gist is that we can use next!(s) to get the next n elements, for an n-dimensional sequence.

julia> using Sobol

julia> s = SobolSeq(2)
2-dimensional Sobol sequence on [0,1]^2

julia> N = 10_000_000
10000000

julia> 4 * count(hypot(next!(s)...) < 1 for _ in 1:N) / N
3.1415952
Related