# Is there a formula for computing median?

Is there an equivalent of the mean formula:

$$\mathrm{mean} = \cfrac{1}{N} \sum_{i=1}^{N} X_i$$

for median?

If you define $O_1, O_2, \ldots, O_N$ to be the sorted version of your original data $X_1, X_2, \ldots, X_N$, then the median is defined as:

$$\mathrm{Median}(\{O_1, O_2, \ldots, O_N\}) = \left\{\begin{array}{ll} O_{(N+1)/2} & \mathrm{if}~N~\mathrm{is~odd} \\ (O_{N/2}+O_{N/2+1})/2 & \mathrm{otherwise}\end{array}\right.$$

Without ordering your data, you can use the definition of the geometric median to define the median in one dimension:

$$\mathrm{Median}(\{X_1, X_2, \ldots, X_N\}) = \arg\min_{y} \sum_{i=1}^N \big|X_i-y\big|$$

Note that this does not necessarily define a unique median when there are an even number of points; for instance any number $y\in[3, 4]$ optimizes the objective with $X = \{2, 3, 4, 5\}$.

• The form for $N$ even is not the only answer - just a convention used. Any value between $O_{N/2}$ and $O_{N/2+1}$ could reasonably be called a "median" – probabilityislogic Apr 25 '16 at 1:08
• @probabilityislogic For sure. I've added the geometric median definition, which is not necessarily unique for $N$ even. – josliber Apr 25 '16 at 1:09

One alternative way to express the mean is the "least squares" estimate:

$$\sum_{i=1}^N (X_i - m)^2$$

Choosing $m$ to be the mean gives the smallest value of the sum of squared errors.

Now the median can be expressed as the "least absolute deviations" estimate:

$$\sum_{i=1}^N |X_i - m|$$

Choosing $m$ to be the median gives the smallest value of the sum of absolute errors.

The median is the value corresponding to the half quantile, that is half of the values are higher, half are lower (pardon me for ignoring cases with equality or when the set is even...). Such that given that the pdf $p_X$ of the data set $X_1 \cdot X_n$ is known, then the cumulative distribution is easily evaluated. Noting $P_X$ this function, then $$median = P_X^{-1}(\frac 1 2)$$

Take for instance the case for angles in this method used in this review paper for histogram equalization. The lower left panel shows the pdf $p(\theta)$ of angles in a set of natural images. $P(\theta)$ is the cumulative distribution and the median is the value of $\theta$ corresponding to the value $1/2$, that is approximately $0$ in that case.