Please enable JavaScript to use CodeHS

Coding for High School Math

Coding for Statistics

Statistics turns a pile of numbers into insight. Code can find the center, spread, and shape of a data set in milliseconds and show how two variables move together.

High School Math ~12 min Statistics
Center

Center and spread

Three numbers describe the center of a data set:

  • Mean: the average, μ = Σx / n.
  • Median: the middle value when the data is sorted.
  • Mode: the most common value.

To describe spread, use the range (max - min) and the interquartile range. These tell you how spread out the numbers are around the center.

Spread

Variance and standard deviation

The variance measures how far each number is from the mean, squared and averaged:

σ² = Σ(xᵢ - μ)² / n

Because the units are squared, we often take the square root to get the standard deviation:

σ = √(Σ(xᵢ - μ)² / n)

A small standard deviation means the data is tightly packed. A large standard deviation means the data is spread out.

Regression

Fitting a line to data

If you have pairs of numbers like hours studied and test scores, a scatter plot shows the relationship. A regression line predicts one value from the other.

One simple way to fit a line is to compute the correlation between x and y, then adjust the slope to match the spread:

m = r · (σy / σx)

b = ȳ - m · x̄

This is called least-squares regression. The line minimizes the total distance to all the points.

Interactive

Interactive stats explorer

Enter a list of numbers separated by commas. The tool will sort the data, compute the mean, median, variance, and standard deviation, and show each step.


    
Code It

Statistics in Python

These functions break every formula into simple steps. First the center, then the spread, then the prediction line.

statistics.py
import math

def mean(data):
    return sum(data) / len(data)

def standard_deviation(data):
    mu = mean(data)
    squared_diffs = [(x - mu)**2 for x in data]
    variance = sum(squared_diffs) / len(data)
    return math.sqrt(variance)

def linear_regression(xs, ys):
    xbar = mean(xs)
    ybar = mean(ys)
    num = sum((x-xbar)*(y-ybar) for x, y in zip(xs, ys))
    den = sum((x-xbar)**2 for x in xs)
    m = num / den
    b = ybar - m * xbar
    return m, b

scores = [5, 8, 12, 6, 15, 9, 11]
print("mean", mean(scores))
print("std dev", standard_deviation(scores))
Output
mean 9.428571428571429
std dev 3.112104929734028

The regression function finds the line that best predicts y from x. Each helper uses the one before it, so the code stays small and readable.

Check Yourself

Quick quiz

1. What does standard deviation measure?

2. Which formula gives the mean?

3. In a regression line y = mx + b, what does b represent?

Keep learning

Statistics handles data. Next, use code to generate and sum number patterns.

Part of the “Coding for High School Math” series.