Histograms

Intuition

A histogram groups numbers into bins (intervals) and counts how many fall in each — a quick picture of a distribution's shape: where it peaks, how wide it is, whether it is skewed.

Precise explanation

With range [lo,hi][\text{lo}, \text{hi}] and kk bins, width w=(hi−lo)/kw = (\text{hi}-\text{lo})/k and edges ej=lo+jwe_j = \text{lo} + j w for j=0..kj = 0..k. Bin jj is the half-open interval [ej,ej+1)[e_j, e_{j+1}), except the last bin, which is closed [ek−1,ek][e_{k-1}, e_k] so the maximum value is counted. This is the same convention NumPy's np.histogram uses.

Index of value xx: j=⌊(x−lo)/w⌋j = \lfloor (x - \text{lo})/w \rfloor, then clamp j=kj = k to k−1k-1. Values below lo or above hi are ignored.

If lo/hi are not given, use the data's min and max. If they are equal, the width is zero; a common convention (used here) is to widen the range to [lo−0.5,hi+0.5][\text{lo}-0.5, \text{hi}+0.5].

Four-bin histogram 2531

Figure (original): counts per bin; the last bin includes its right edge.

Worked example

data [1, 2, 2, 3, 4, 5], 2 bins over [1, 5]: width 2, edges [1, 3, 5]. Bin 0 = [1, 3): 1, 2, 2 → 3. Bin 1 = [3, 5]: 3, 4, 5 → 3.

Common mistakes

  • Dropping the maximum value because every bin is half-open.
  • Floating-point edges such as 0.1 + 0.2; compute edges as lo + j*w.
  • Too few/too many bins hiding the shape.

Why this matters

Histograms are the first look at any feature, the basis of intensity histograms in images (CV-09), and the binning used in calibration plots.

Library implementation

np.histogram(data, bins=k, range=(lo, hi)) uses the same rule: equal-width bins, each half-open [a, b) except the last, which also includes hi; when lo == hi it widens the range by 0.5 on each side, exactly as this exercise specifies. It returns (counts, edges) — the opposite order to your function.

References