<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amelia Taylor on Medium]]></title>
        <description><![CDATA[Stories by Amelia Taylor on Medium]]></description>
        <link>https://medium.com/@amelia.taylor.xyz?source=rss-77c5dda6f1e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oN-4RpxraW6dhq6FNEIQrw.jpeg</url>
            <title>Stories by Amelia Taylor on Medium</title>
            <link>https://medium.com/@amelia.taylor.xyz?source=rss-77c5dda6f1e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:47:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amelia.taylor.xyz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Monte Carlo Integration in NumPy: Watch a Grid Lose in Ten Dimensions]]></title>
            <link>https://medium.com/@amelia.taylor.xyz/monte-carlo-integration-python-05f6053cbacc?source=rss-77c5dda6f1e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/05f6053cbacc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Amelia Taylor]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 14:20:01 GMT</pubDate>
            <atom:updated>2026-10-09T14:59:07.930Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A six-line NumPy integrator, and a grid that puts a 10-dimensional ball’s volume at exactly 1.000 when the truth is 2.550.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiBkmD3kkdaWiRV7wfdBtA.png" /><figcaption><em>Random darts on a quarter circle, and the running estimate of π they produce settling onto the true value.</em></figcaption></figure><p>You’ll build a six-line Monte Carlo integrator in Python, check it on two ten-dimensional integrals with known answers, and pit it against an equal-sized grid. You’ll also measure what it charges: a hundred times the points for each extra digit, whatever the dimension.</p><h3>Throw a million darts at a quarter circle</h3><p>Monte Carlo integration estimates an integral as the region’s volume times the integrand’s average at random points. Start from an area ratio. A quarter circle of radius 1, centred on a corner of the unit square, covers π/4 of it. Multiply the fraction of random points under the arc by four and you have π.</p><p>You need only NumPy. The block draws a million points with a seeded generator, scores each one 4 if it lands inside and 0 if not, and averages the scores. It also keeps the running average for the figure and sets P and SIGMA aside. Then it draws from the same stream up to a hundred million, keeping only the hit count:</p><pre>import numpy as np<br> <br>P = np.pi / 4                               # chance that one point lands inside<br>SIGMA = 4 * np.sqrt(P * (1 - P))            # scatter of one score of 4 or 0<br>CHUNK = 10**6<br> <br>rng = np.random.default_rng(1)<br>xy = rng.random((CHUNK, 2))<br>inside = (xy**2).sum(axis=1) &lt;= 1<br>scores = 4.0 * inside<br>n_pts = np.arange(1, CHUNK + 1)<br>running = np.cumsum(scores) / n_pts<br>s_open = scores.std(ddof=1)<br>print(f&quot;N = {CHUNK:&gt;11,}   estimate = {running[-1]:.4f} ± {s_open / np.sqrt(CHUNK):.4f}&quot;)<br> <br># continue the same stream to 10^8 points, a million at a time<br>hits, total = inside.sum(), CHUNK<br>for _ in range(99):<br>    hits += ((rng.random((CHUNK, 2))**2).sum(axis=1) &lt;= 1).sum()<br>    total += CHUNK<br>p_hat = hits / total<br>print(f&quot;N = {total:&gt;11,}   estimate = {4 * p_hat:.5f} ± {4 * np.sqrt(p_hat * (1 - p_hat) / (total - 1)):.5f}&quot;)</pre><pre>N =   1,000,000   estimate = 3.1432 ± 0.0016<br>N = 100,000,000   estimate = 3.14154 ± 0.00016</pre><p>The million-point estimate, 3.1432, is right to three digits. The hundred-million line adds the fourth, 3.14154, with an error bar ten times narrower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lx3NQf7iQtXQRMtR_-hyQ.png" /><figcaption><em>The first thousand darts, and the running estimate settling on π as N grows to a million.</em></figcaption></figure><p>Both ± values are the sample standard deviation of the 0-or-4 scores over √<em>N</em>, the second in closed form from the hit fraction <em>p̂</em> because only the count was kept. The two estimates sit 1.0 and 0.3 error bars off π, so seed 1 is no outlier.</p><h3>Run it a hundred times and draw the bands</h3><p>Each dart scores 4 with probability <em>p</em> = π/4 and 0 otherwise. Alone, a score misses π by 0.86 or by 3.14, and its standard deviation is <em>σ</em> = 4√(<em>p</em>(1 − <em>p</em>)) = 1.642. The estimate after <em>N</em> darts averages <em>N</em> independent scores, which shrinks the scatter to <em>σ</em>/√<em>N</em>.</p><p>Call <em>σ</em>/√<em>N</em> the standard error: the typical distance between your estimate and the truth after <em>N</em> samples. About 68 % of runs should land within one standard error and 95 % within two. The block runs a hundred experiments of 105 darts each and counts how many end inside each band:</p><pre>N_RUN, RUNS = 10**5, 100<br>rng = np.random.default_rng(2026)<br>n_run = np.arange(1, N_RUN + 1)<br>runs = np.array([np.cumsum(4.0 * ((rng.random((N_RUN, 2))**2).sum(axis=1) &lt;= 1)) / n_run<br>                 for _ in range(RUNS)])<br> <br>half = SIGMA / np.sqrt(N_RUN)<br>miss = np.abs(runs[:, -1] - np.pi)<br>in1, in2 = (miss &lt; half).sum(), (miss &lt; 2 * half).sum()<br>print(f&quot;inside π ± σ/√N at N = 10^5:  {in1:3d} of {RUNS}&quot;)<br>print(f&quot;inside π ± 2σ/√N at N = 10^5: {in2:3d} of {RUNS}&quot;)<br>print(f&quot;opening run: s = {s_open:.3f}   true σ = {SIGMA:.3f}&quot;)</pre><pre>inside π ± σ/√N at N = 10^5:   69 of 100<br>inside π ± 2σ/√N at N = 10^5:  98 of 100<br>opening run: s = 1.641   true σ = 1.642</pre><p>The counts are 69 and 98. A normal distribution expects 68 and 95.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQC58TSr0M-hglmcYLHHQg.png" /><figcaption><em>A hundred independent runs, with the one- and two-standard-error bands π ± σ/√N and π ± 2σ/√N drawn around π. Near N = 100 more runs escape below the outer band than above, since a mean of a hundred 0-or-4 scores with p &gt; 1/2 is still skewed low.</em></figcaption></figure><p>Those bands needed the true π and <em>σ</em>. A real calculation estimates <em>σ</em> from its own scores, and the last line puts that estimate, <em>s</em> = 1.641, beside <em>σ</em> = 1.642.</p><h3>Give a grid the same number of points</h3><p>A grid spaces its points evenly where random darts bunch up by chance, so it looks like the obvious upgrade. Test it on an equal budget, first on a line, then in ten dimensions. On a line π = 4∫01√(1 − <em>x</em>2) d<em>x</em>, and the midpoint rule averages the integrand at the centres of <em>N</em> equal cells of width <em>h</em> = 1/<em>N</em>. The block computes both errors at six sizes and prints <em>N</em> = 1,000:</p><pre># one dimension: pi as the integral of 4 sqrt(1 - x^2) over [0, 1]<br>f1 = lambda x: 4 * np.sqrt(1 - x**2)<br>rng = np.random.default_rng(2026)<br>Ns = 10 ** np.arange(1, 7)<br>err_grid = np.array([abs(f1((np.arange(N) + 0.5) / N).mean() - np.pi) for N in Ns])<br>fx = [f1(rng.random(N)) for N in Ns]<br>se_mc = np.array([v.std(ddof=1) / np.sqrt(v.size) for v in fx])<br>print(f&quot;1D, N = 1,000: grid error {err_grid[2]:.1e}   Monte Carlo standard error {se_mc[2]:.3f}&quot;)</pre><pre>1D, N = 1,000: grid error 1.1e-05   Monte Carlo standard error 0.029</pre><p>In one dimension the grid does win: its error is 1.1 × 10–5 against Monte Carlo’s 0.029.</p><h3>Ten dimensions</h3><p>The unit ball, <em>x</em>12 + … + <em>x</em>102 ≤ 1, sits in the cube [−1, 1]10. Count the fraction of cube points that pass the inequality, multiply by the cube’s volume 210, and you have the ball’s. A grid with <em>k</em> points per axis has <em>k</em>10 points, about 60 million at <em>k</em> = 6, so grid_volume never builds them. The cell centres on one axis sit at (2<em>i</em> + 1 − <em>k</em>)/<em>k</em>, so in units of 1/<em>k</em>2 each squared coordinate is the integer (2<em>i</em> + 1 − <em>k</em>)2. np.bincount turns those integers into a histogram, and convolving two histograms gives the histogram of their sums, so ten convolutions count how many grid points have each sum of squares. A sum of at most 1, which is <em>k</em>2 in these units, is the first <em>k</em>2 + 1 entries of counts.</p><p>In the Monte Carlo loop the method is the hits += line, the hit fraction p_hat, and the two appends, volume V * p_hatand error V * np.sqrt(p_hat * (1 - p_hat) / (done - 1)). The checkpoints and while loop are bookkeeping for the figure:</p><pre># ten dimensions: the unit ball inside [-1, 1]^10<br>D, V = 10, 2.0**10<br>EXACT = np.pi**5 / 120<br> <br>def grid_volume(k, d=D):<br>    &quot;&quot;&quot;Ball volume from a k^d midpoint grid, by counting sums of squares instead of building the grid.&quot;&quot;&quot;<br>    sq = (2 * np.arange(k) + 1 - k) ** 2          # squared coordinates in units of 1/k^2, exact integers<br>    counts = np.ones(1, dtype=np.int64)<br>    for _ in range(d):<br>        counts = np.convolve(counts, np.bincount(sq))<br>    return V * counts[: k * k + 1].sum() / k**d<br> <br>ks = np.arange(2, 7)<br>grid_vol = np.array([grid_volume(k) for k in ks])<br> <br>checkpoints = np.unique(np.geomspace(1e3, 1e7, 9).astype(int))<br>rng = np.random.default_rng(2026)<br>hits, done, mc_vol, mc_err = 0, 0, [], []<br>for N in checkpoints:<br>    while done &lt; N:<br>        m = min(CHUNK, N - done)<br>        hits += ((rng.uniform(-1, 1, (m, D))**2).sum(axis=1) &lt;= 1).sum()<br>        done += m<br>    p_hat = hits / done<br>    mc_vol.append(V * p_hat)<br>    mc_err.append(V * np.sqrt(p_hat * (1 - p_hat) / (done - 1)))<br>for N, v, e in zip(checkpoints, mc_vol, mc_err):<br>    if N in (10**6, 10**7):<br>        print(f&quot;10D, N = {N:&gt;10,}: Monte Carlo {v:.3f} ± {e:.3f}   exact {EXACT:.4f}&quot;)<br>print(&quot;10D grid volumes, k = 2 to 6:&quot;, &quot;  &quot;.join(f&quot;{v:.2f}&quot; for v in grid_vol))</pre><pre>10D, N =  1,000,000: Monte Carlo 2.526 ± 0.051   exact 2.5502<br>10D, N = 10,000,000: Monte Carlo 2.545 ± 0.016   exact 2.5502<br>10D grid volumes, k = 2 to 6: 0.00  3.49  1.00  3.07  3.23</pre><p>The five grids scatter from 0.00 to 3.49 around a true 2.550. The grid prints no warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWfaPkOa2GiwG3-Cah1WDw.png" /><figcaption><em>Left: in one dimension the grid’s error falls with slope −3/2. Each orange dot is the actual miss of one random run, and the upper dashed line is the standard error σ_f/√N the block prints, with σ_f the scatter of 4√(1 − x2), not the darts’ 1.642. Right: in ten dimensions the grid values jump around the exact volume while Monte Carlo closes in on it.</em></figcaption></figure><p>Check <em>k</em> = 4 in your head. The centres on each axis are ±0.25 and ±0.75. Put one coordinate at ±0.75: it squares to 0.5625, and the nine remaining coordinates contribute no less than 9 × 0.0625 = 0.5625 on top, so the point sits at 1.125 or beyond, outside. Only points with all ten coordinates at ±0.25 count, 210 of the 410, so the volume is 210 × 210/410 = 1.000. Try <em>k</em> = 2 the same way: ±0.5 squared ten times gives 2.5 for every point, so the count inside is zero.</p><p>Shrink the cell width <em>h</em> and a grid rule’s error falls as <em>h</em>ᵖ for some fixed <em>p</em>, the rule’s order, which a log-log plot shows as the slope −<em>p</em>. Spread <em>N</em> points over <em>d</em> axes and each gets <em>N</em>^(1/<em>d</em>), so <em>h</em> ∝ <em>N</em>^(−1/<em>d</em>) and the error ∝ <em>N</em>^(−<em>p</em>/<em>d</em>). Monte Carlo’s <em>N</em>^(−1/2) wins once <em>d</em> &gt; 2<em>p</em>. For the midpoint rule <em>p</em> = 2, so the rates tie at <em>d</em> = 4, and at <em>d</em> = 10 the grid’s error shrinks only as <em>N</em>^(−1/5). (In 1D the slope is −3/2, not −2, because √(1 − <em>x</em>2) is infinitely steep at <em>x</em> = 1.)</p><p>Despite the ball’s hard edge, the midpoint rule keeps order 2 on average. Each cell the surface crosses is an all-or-nothing vote, counted whole if its centre is in and not at all if it’s out. In ten dimensions the many cut cells vote both ways and the tally nearly balances. On a line a jump straddles a single cell, and its lone vote, worth up to half a cell width, stands as an error proportional to <em>h</em>. The leftover error’s sign depends on where the lattice meets the sphere. Print the larger grids:</p><pre>print(&quot; k                          N    grid volume      error&quot;)<br>for k in [2, 3, 4, 5, 6, 7, 15, 16, 32, 64]:<br>    v = grid_volume(k)<br>    print(f&quot;{k:2d} {k**D:&gt;26,}    {v:11.3f}    {100 * (v - EXACT) / EXACT:+7.2f} %&quot;)</pre><pre>k                          N    grid volume      error<br> 2                      1,024          0.000    -100.00 %<br> 3                     59,049          3.486     +36.68 %<br> 4                  1,048,576          1.000     -60.79 %<br> 5                  9,765,625          3.071     +20.41 %<br> 6                 60,466,176          3.226     +26.48 %<br> 7                282,475,249          2.775      +8.83 %<br>15            576,650,390,625          2.600      +1.97 %<br>16          1,099,511,627,776          2.452      -3.85 %<br>32      1,125,899,906,842,624          2.526      -0.96 %<br>64  1,152,921,504,606,846,976          2.544      -0.24 %</pre><p>Between <em>k</em> = 15 and 16 the error changes sign, and each doubling from 16 to 32 to 64 quarters it, the order-2 rate. Monte Carlo’s error bar at a million points was 2 %. At <em>k</em> = 7 the grid has spent 2.8 × 108 evaluations and is still 8.8 % high, more than four error bars. It gets under 2 % only at <em>k</em> = 15, with 5.8 × 1011 points, roughly half a million times Monte Carlo’s bill.</p><h3>Write the general integrator</h3><p>Back to the opening identity, with <em>V</em> the region’s volume: the average of <em>f</em> is the expected value of <em>f</em>(<em>X</em>) for <em>X</em> uniform on the region, and the mean of <em>N</em> independent draws estimates it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIHnJ1fQRJTtpK9qP0zihw.png" /></figure><p>The darts had <em>V</em> = 1 and <em>f</em> equal to 4 under the arc, 0 elsewhere. Let <em>σ_f</em> be the standard deviation of one value of <em>f</em>. Since independent variances add, <em>N</em> values sum to a variance of <em>Nσ_f</em>2. The mean divides that sum by <em>N</em>, and with the factor <em>V</em>the standard error is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_h2I4bKPvFyAbRrUcayzog.png" /></figure><p>The √<em>N</em> is the same in every dimension, while <em>σ_f</em> may change with it.</p><p>Here’s the integrator: the formula above, with the box as the region and one call to f for all <em>n</em> points. It returns the volume-scaled mean and its standard error. The test sets <em>n</em> = 410 to match the four-per-axis grid. The ball&#39;s <a href="https://en.wikipedia.org/wiki/Volume_of_an_n-ball">exact volume</a> is π5/120, where math.gamma(6) supplies 5! = 120. The Gaussian exp(−|<em>x</em>|2) splits into ten identical one-dimensional factors, each ∫-11 e^(−<em>x</em>2) d<em>x</em> = √π erf 1:</p><pre>import math<br> <br>def mc_integrate(f, lo, hi, n, rng):<br>    &quot;&quot;&quot;Integral of f over the box [lo, hi] from n uniform points, and its standard error.&quot;&quot;&quot;<br>    lo, hi = np.asarray(lo, float), np.asarray(hi, float)<br>    volume = np.prod(hi - lo)<br>    fx = f(rng.uniform(lo, hi, (n, lo.size)))       # one row per point<br>    return volume * fx.mean(), volume * fx.std(ddof=1) / np.sqrt(n)<br> <br>rng = np.random.default_rng(2026)<br>d, n = 10, 4**10<br>lo, hi = -np.ones(d), np.ones(d)<br>ball = lambda x: ((x**2).sum(axis=1) &lt;= 1).astype(float)<br>gauss = lambda x: np.exp(-(x**2).sum(axis=1))<br> <br>ball_exact = np.pi ** (d / 2) / math.gamma(d / 2 + 1)<br>gauss_exact = (math.sqrt(math.pi) * math.erf(1)) ** d<br>ball_mc, ball_se = mc_integrate(ball, lo, hi, n, rng)<br>gauss_mc, gauss_se = mc_integrate(gauss, lo, hi, n, rng)<br>print(f&quot;ball,     Monte Carlo:     {ball_mc:7.3f} ± {ball_se:.3f}   exact {ball_exact:7.3f}&quot;)<br>print(f&quot;ball,     4-per-axis grid: {grid_volume(4):7.3f}           exact {ball_exact:7.3f}&quot;)<br>print(f&quot;Gaussian, Monte Carlo:     {gauss_mc:7.3f} ± {gauss_se:.3f}   exact {gauss_exact:7.3f}&quot;)<br>print(f&quot;distance from exact in error bars: ball {(ball_mc - ball_exact) / ball_se:+.2f}, &quot;<br>      f&quot;Gaussian {(gauss_mc - gauss_exact) / gauss_se:+.2f}&quot;)</pre><pre>ball,     Monte Carlo:       2.518 ± 0.050   exact   2.550<br>ball,     4-per-axis grid:   1.000           exact   2.550<br>Gaussian, Monte Carlo:      55.291 ± 0.054   exact  55.269<br>distance from exact in error bars: ball -0.66, Gaussian +0.40</pre><p>The last printed line is the check: −0.66 and +0.40 error bars, both under one. On the same 410 points the four-per-axis grid misses by 61 %. <em>σ_f</em> explains why the ball’s error bar is 2 % and the Gaussian’s 0.1 %. The ball fills 0.25 % of the cube, one point in four hundred, so <em>f</em> is almost always 0, a wide scatter next to so small a mean, while the Gaussian changes smoothly and scatters far less.</p><h3>What you just built</h3><p>You now have mc_integrate, six lines that integrate any vectorized function over a box of any dimension with an error bar from the same samples. For your own integral, replace the lambda with your function and lo, hi with your box.</p><p>Then break its one assumption, independent samples. A Markov chain’s samples each remember the last, so <em>N</em> of them are worth fewer independent draws, and the standard error divides by the square root of that smaller count. With correlation 0.9i at lag <em>i</em> the count is <em>N</em>/19, and an error bar that treats the draws as independent is √19, about four times, too small. Or try <a href="https://docs.scipy.org/doc/scipy/reference/stats.qmc.html">scipy.stats.qmc</a>, whose points spread evenly without lining up like a grid, and compare its miss from the exact 2.550, ignoring the ±, which assumes independent points.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05f6053cbacc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>