statisticsvectorization

Monte Carlo Estimation of π

The classic Monte Carlo — sample points in a unit square and count how many fall in the inscribed circle.

Almost pure vectorized array math. `rand` maps to `np.random.rand`, logical indexing and `sum` work the same way. The MATLAB row-vs-column vector convention doesn't matter here — everything is scalar at the end.

MATLAB source9 lines
% Estimate pi by sampling
N = 1e6;
x = rand(N, 1);
y = rand(N, 1);
inside = (x.^2 + y.^2) <= 1;
pi_est = 4 * sum(inside) / N;

fprintf('With %d samples, pi ≈ %.6f (error: %.6f)\n', ...
    N, pi_est, abs(pi_est - pi));
Python output (converter-generated)11 lines · 0 flags
import numpy as np

# Estimate pi by sampling
N = 1e6
x = np.random.rand(N, 1)
y = np.random.rand(N, 1)
inside = (x**2 + y**2) <= 1
pi_est = 4 * np.sum(inside) / N

print('With %d samples, pi ≈ %.6f np.arange(error, %.6f + 1)' % (N, pi_est, np.abs(pi_est - pi)))
Implementation notes
Pure numpy. No plotting, fast to run.
Try it on your own MATLAB

Free for 50 lines. Same converter that produced the Python above.

More examples like this, once a week

New canonical conversions and release notes from the converter. One email, no spam.