Monte-Carlo π: a worked solution¶

The worked solution to the second exercise of tutorial 1. Attempt it there first.

Draw a million uniform points in the unit square and count the fraction inside the quarter disk, as one fused reduction: the test is applied to each pair on the way into the sum, so nothing the size of N is ever materialized.

In [1]:
using CUDA

N = 10^6

xr = CUDA.rand(Float64, N)
yr = CUDA.rand(Float64, N)

inside = mapreduce((x, y) -> (x^2 + y^2 <= 1.0), +, xr, yr)

pi_estimate = 4 * inside / N
Out[1]:
3.140772

This notebook was generated using Literate.jl.