Measure spread as the average absolute distance each value sits from the mean. Compute the mean, then average the absolute deviations — dividing by n (not nāˆ’1). By hand, two loops: one for the mean, one for the sum of absolute deviations. With numpy, np.mean(np.abs(x - np.mean(x))) does both in one vectorised expression.

By hand

With the library

np.abs(x - x_mean) subtracts the mean from every element and takes the absolute value in one vectorised step; np.mean(...) then averages the result. Both halves divide by n, so the results match exactly.

naive.py
values = [4, 8, 6, 13, 10, 6, 9]
n = len(values)
total = 0.0
for v in values:
    total = total + v
mean = total / n
abs_sum = 0.0
for v in values:
    abs_sum = abs_sum + abs(v - mean)
mad = abs_sum / n
print('RESULT:', round(mad, 10))
library.py
import numpy as np
from dalib.display import set_display
set_display()

values = [4, 8, 6, 13, 10, 6, 9]
x = np.array(values, dtype=float)
x_mean = float(np.mean(x))
mad = float(np.mean(np.abs(x - x_mean)))
print('mean:', x_mean)
print('RESULT:', round(mad, 10))
mean: 8.0
RESULT: 2.2857142857

Implementation notes

  • MAD divides by n (the full count), not nāˆ’1. There is no Bessel correction because MAD is not trying to estimate a population parameter in the same way variance is.
  • MAD is in the same units as the data (like std) but is more robust to outliers because absolute differences grow linearly while squared differences grow quadratically.
  • statistics.mean(abs(v - mean) for v in values) is the pure-stdlib equivalent, but numpy's vectorised form is faster for large arrays.