Practice · Baseball · Simulated for practice

Batted balls

Five hundred invented, well-elevated batted balls: exit velocity, launch angle, and how far each went. Enough to fit a model by hand and check it the way MCMC in Practice does.

The data

500 rows, 3 columns.

launch_speednumber · mph
Exit velocity off the bat
launch_angleinteger · degrees
Vertical launch angle
hit_distanceinteger · ft
Projected distance of the batted ball

Simulated for practice. Simulated for practice by AthlyticZ (agents/sim_data.py, seed 20261109). License CC BY 4.0. Generated from a documented model with realistic distributions; every name is invented.

Reference chart

The chart, and the code that draws it.

Edit the code and press Run to recompute it in your browser.

Python
This chart is the code's result. Run recomputes it in your browser.
The evidence lower bound as variational inference fits distance against exit velocity: noisy draws and their running mean.

Edit me: Move the learning rate, or set steps to 1000 and run again. Where does it settle?

Data: Batted balls (batted_balls_2026.csv). Simulated for practice by AthlyticZ (agents/sim_data.py, seed 20261109). License CC BY 4.0.

The code runs in your browser on Pyodide; nothing you type leaves the page.

Starter code

import pandas as pd

balls = pd.read_csv("data/batted_balls_2026.csv")
balls.describe().round(1)
Three questions

Easy, medium, hard.

Try each before opening the hint; open the worked solution only after your own attempt.

  1. Easy

    Bucket launch angle into five-degree bands. Which band carries the ball farthest at a given exit velocity?

    Hint

    pd.cut the angle, then group by band and report the mean distance per mph of exit velocity, or the mean distance for balls hit 100 mph or harder.

    Worked solution
    import pandas as pd
    
    b = pd.read_csv("data/batted_balls_2026.csv")
    out = (b.query("launch_speed >= 100")
             .assign(band=lambda d: pd.cut(d.launch_angle, range(15, 45, 5), right=False))
             .groupby("band", observed=True)
             .agg(balls=("hit_distance", "size"), distance=("hit_distance", "mean"))
             .round(1))
    print(out.to_string())

    Output, from running this code on the dataset when the page was built

    balls  distance
    band                     
    [15, 20)     29     355.7
    [20, 25)     31     388.7
    [25, 30)     33     400.8
    [30, 35)     28     395.8
    [35, 40)     34     372.9
  2. Medium

    Fit distance on exit velocity and a squared launch-angle term centered on the best angle. Report the coefficients and the residual standard deviation.

    Hint

    Center the angle at 28 degrees, square it, and solve the least-squares problem with numpy.linalg.lstsq on a design matrix with an intercept.

    Worked solution
    import numpy as np
    import pandas as pd
    
    b = pd.read_csv("data/batted_balls_2026.csv")
    X = np.column_stack([np.ones(len(b)), b.launch_speed, (b.launch_angle - 28) ** 2])
    beta, *_ = np.linalg.lstsq(X, b.hit_distance, rcond=None)
    resid = b.hit_distance - X @ beta
    print("intercept, ft per mph, ft per squared degree:", np.round(beta, 3))
    print("residual sd, ft:", round(float(resid.std(ddof=3)), 1))

    Output, from running this code on the dataset when the page was built

    intercept, ft per mph, ft per squared degree: [-122.397    5.077   -0.459]
    residual sd, ft: 14.1
  3. Hard

    Write a Metropolis sampler for the intercept and the exit-velocity slope (residual sd fixed at your medium answer). Report the posterior mean, a 90% interval for the slope, and the acceptance rate. Tune the step until it sits near 30 percent.

    Hint

    Work on centered exit velocity so intercept and slope are nearly independent; propose both at once with a small normal step and keep the log posterior, not the posterior.

    Worked solution
    import numpy as np
    import pandas as pd
    
    b = pd.read_csv("data/batted_balls_2026.csv")
    x = b.launch_speed - b.launch_speed.mean()
    z = (b.launch_angle - 28) ** 2
    y = b.hit_distance + 0.45 * z          # the angle term from the medium answer, held fixed
    sigma = 14.0
    def logp(t):
        return -0.5 * np.sum((y - t[0] - t[1] * x) ** 2) / sigma**2
    rng = np.random.default_rng(3)
    t, lp, keep, acc = np.array([350.0, 4.0]), None, [], 0
    lp = logp(t)
    for i in range(6000):
        prop = t + rng.normal(0, [1.6, 0.21])
        lq = logp(prop)
        if np.log(rng.random()) < lq - lp:
            t, lp = prop, lq; acc += 1
        if i >= 1000:
            keep.append(t.copy())
    s = np.array(keep)
    lo, hi = np.percentile(s[:, 1], [5, 95])
    print(f"slope: mean {s[:, 1].mean():.3f} ft per mph, 90% interval {lo:.3f} to {hi:.3f}")
    print(f"acceptance rate {acc / 6000:.2f}")

    Output, from running this code on the dataset when the page was built

    slope: mean 5.078 ft per mph, 90% interval 4.905 to 5.247
    acceptance rate 0.25
Extension

Bring in an AI agent.

Ask an agent to rewrite your sampler in PyMC and to run the diagnostics MCMC in Practice teaches (trace plots, r-hat, effective sample size, a posterior predictive check). Then ask it where its posterior and yours disagree and why; a correct answer names the fixed residual sd in your version.

Where the method is taught

MCMC in Practice. Every dataset in the practice library names its session the same way.

Keep up

One email when something new arrives.

A short welcome note, a few session picks over two weeks, then only the updates you signed up for. Reply stop any time.