% Monte Carlo estimate of pi from 20 BILLION samples, drawn in 2000 batches. % (Pasting into MATLAB? Cut batches to ~50 -- generating this many doubles % takes CPUs minutes, which is rather the point.) % The draws, the comparison and the mean all fuse into one reduction pass, % so each batch's 10 million points are generated, tested and counted % without ever touching GPU memory. n = 10000000; batches = 2000; s = zeros(1, 1); tic; for k = 1:batches s = s + mean(((2*rand(n,1) - 1).^2 + (2*rand(n,1) - 1).^2) <= 1); end t = toc; fprintf('pi ~ %.6f (%.1f billion samples, %.0f million samples/sec)\n', ... 4*s/batches, batches*n/1e9, batches*n/1e6/t);