### 54 releases (stable)

3.0.11 | Apr 27, 2024 |
---|---|

3.0.9 | Mar 12, 2024 |

3.0.4 | Dec 27, 2023 |

3.0.2 | Oct 29, 2023 |

0.0.6 | Feb 25, 2022 |

#**58** in Algorithms

**2,321** downloads per month

Used in **10** crates
(2 directly)

**BSD-3-Clause**

48KB

760 lines

# Medians

**by Libor Spacek**

Fast algorithm for finding medians of one dimensional data, implemented in 100% safe Rust.

`use` `medians``::``{``*``,``algos``::``*``}``;`

## Introduction

Finding medians is a common task in statistics and data analysis. At least it ought to be, because median is a more stable measure of central tendency than mean. Similarly,

(median of absolute differences) is a more stable measure of data spread than standard deviation, which is dominated by squared outliers. Median and `mad`

are not used nearly enough mostly for practical historical reasons: they are more difficult to compute. The fast algorithms presented here provide remedy for this situation.`mad`

We argued in

, that using the Geometric Median is the most stable way to characterise multidimensional data. The one dimensional case is addressed here.`rstats`

See

for examples of usage. Their automatically generated output can also be found by clicking the 'test' icon at the top of this document and then examining the latest log.`tests.rs`

## Outline Usage

Best methods/functions to be deployed, depending on the end type of data (i.e. type of the items within the input vector/slice).

-> function`u8``medianu8`

-> function`u64``medianu64`

-> methods of trait Medianf64`f64`

custom quantifiable to u64 -> method`T`

of trait`uqmedian``Median`

custom comparable by`T`

-> method`c`

of trait`qmedian_by``Median`

custom comparable but not quantifiable -> method`T`

of trait`median_by`

.`Median`

## Algorithms Analysis

Short primitive types are best dealt with by radix search. We have implemented it for

:`u8`

`///` Median of primitive type u8 by fast radix search
`pub` `fn` `medianu8``(``s``:` `&`[`u8`]`)`` ``->` `Result``<`ConstMedians`<``u8``>`, Me`>`

More complex data types require general comparison search, see

. Median can be found naively by sorting the list of data and then picking its midpoint. The best comparison sort algorithms have complexity `median_by`

. However, faster median algorithms with complexity `O (n*log(n))`

`O``(`n`)`

are possible. They are based on the observation that data need to be all sorted, only partitioned and counted off. Therefore, the naive sort method can not compete and has been deleted as of version 2.0.0.Currently considered to be the 'state of the art' comparison algorithm is Floyd-Rivest (1975): Median of Medians. This divides the data into groups of five items, finds median of each group by sort, then finds medians of five of these medians, and so on, until only one remains. This is then used as the pivot for partitioning of the original data. Such pivot will produce good partitioning, though not perfect. Counting off and iterating is still necessary.

However, finding the best pivot estimate is not the main objective. The real objective is to eliminate (count off) eccentric data items as fast as possible. Therefore, the expense of estimating the pivot is highly relevant. It is possible to use less optimal pivots, yet to find the medians faster on average. In any case, efficient partitioning is a must.

Let our average ratio of items remaining after one partitioning be

and the Floyd-Rivest's be `rs`

. Typically, `rf`

, i.e. `1``/``2` `<=` rf `<=` rs `<` `1`

is more optimal, being nearer to the perfect partitioning ratio of `rf`

. However, suppose that we can perform two partitions in the time it takes Floyd-Rivest to do one (because of their expensive pivot selection process). Then it is enough for better performance that `1``/``2`

, which is perfectly possible and seems to be born out in practice. For example, `rs ^2 < rf`

`rf``=``0.``65`

(nearly optimal), `rs``=``0.``8`

(deeply suboptimal), yet `rs``^``2` `<` rf

.Nonetheless, on large datasets, we do devote some of the overall computational effort to pivot selection.

We introduce another new algorithm, implemented as function

:`medianu64`

`///` Fast medians of u64 end type by binary partitioning
`pub` `fn` `medianu64``(``s``:` `&``mut` [`u64`]`)`` ``->` `Result``<`ConstMedians`<``u64``>`, Me`>`

on

data, this runs about twice as fast as the general purpose pivoting of `u64`

. The data is partitioned by individual bit values, totally sidestepping the expense of the pivot estimation. The algorithm generally converges well. However, when the data happens to be all bunched up within a small range of values, it will slow down.`median_by`

### Summary of he main features of our general median algorithm

- Linear complexity.
- Fast (in-place) iterative partitioning into three subranges (lesser,equal,greater), minimising data movements and memory management.
- Simple pivot selection strategy: median of three samples (requires only three comparisons). Really poor pivots occur only rarely during the iterative process. For longer data, we deploy median of three medians.

## Trait Medianf64

`///` Fast 1D medians of floating point data, plus related methods
`pub` `trait` `Medianf64` `{`
`///` Median of f64s, NaNs removed
`fn` `medf_checked``(``self``)`` ``->` `Result``<``f64`, Me`>``;`
`///` Median of f64s, including NaNs
`fn` `medf_unchecked``(``self``)`` ``->` `f64``;`
`///` Iterative weighted median
`fn` `medf_weighted``(``self`, `ws``:` `Self`, `eps``:` `f64``)`` ``->` `Result``<``f64`, Me`>``;`
`///` Zero mean/median data produced by subtracting the centre
`fn` `medf_zeroed``(``self`, `centre``:` `f64``)`` ``->` `Vec``<``f64``>``;`
`///` Median correlation = cosine of an angle between two zero median vecs
`fn` `medf_correlation``(``self`, `v``:` `Self``)`` ``->` `Result``<``f64`, Me`>``;`
`///` Median of absolute differences (MAD).
`fn` `madf``(``self`, `centre``:` `f64``)`` ``->` `f64``;`
`}`

## Trait Median

These methods are provided especially for generic, arbitrarily complex and/or large data end-types. The data is never copied during partitioning, etc.

Most of its methods take a comparison closure

which returns an ordering between its arguments of generic type `c`

. This allows comparisons in any number of different ways between any custom types.`&`T

Most of its methods take a quantify closure

, which converts its generic argument to f64. This facilitate not just standard Rust `q`

and `as`

conversions but also any number of flexible ways of quantifying more complex custom data types.`.``into``(``)`

Weaker partial ordinal comparison is used instead of numerical comparison. The search algorithm remains the same. The only additional cost is the extra layer of referencing to prevent the copying of data.

`median_by``(``)`

For all end-types quantifiable to f64, we simply averaged the two midpoints of even length data to obtain a single median (of type

). When the data items are unquantifiable to `f64`

, this is no longer possible. Then `f64`

should be used. It returns both middle values within `median_by`

enum type, the lesser one first:`Medians`

`///` Enum for results of odd/even medians
`pub` `enum` `Medians`<'a, T> `{`
`///` Odd sized data results in a single median
Odd`(``&``'a` T`)``,`
`///` Even sized data results in a pair of (centered) medians
Even`(``(``&``'a` T`,` `&``'a` T`)``)``,`
`}`

`///` Fast 1D generic medians, plus related methods
`pub` `trait` `Median`<'a, T> `{`
`///` Median by comparison `c`, at the end quantified to a single f64 by `q`
`fn` `qmedian_by``(`
`self`,
`c``:` `&``mut` impl FnMut`(`&`T``,` &`T``)` -> Ordering,
`q``:` impl Fn`(`&`T``)` -> `f64`,
`)`` ``->` `Result``<``f64`, Me`>``;`
`///` Median of types quantifiable to u64 by `q`, at the end converted to a single f64.
`///` For data that is already `u64`, use function `medianu64`
`fn` `uqmedian``(`
`self`,
`q``:` impl Fn`(`&`T``)` -> `u64`,
`)`` ``->` `Result``<``f64`, Me`>``;`
`///` Median by comparison `c`, returns odd/even result
`fn` `median_by``(``self`, `c``:` `&``mut` impl FnMut`(`&`T``,` &`T``)` -> Ordering`)`` ``->` `Result``<`Medians`<``'a`, T`>`, Me`>``;`
`///` Zero mean/median data, produced by subtracting the centre
`fn` `zeroed``(``self`, `centre``:` `f64`, `quantify``:` impl Fn`(`&`T``)` -> `f64``)`` ``->` `Result``<``Vec``<``f64``>`, Me`>``;`
`///` Median correlation = cosine of an angle between two zero median Vecs
`fn` `med_correlation``(`
`self`,
`v``:` `Self`,
`c``:` `&``mut` impl FnMut`(`&`T``,` &`T``)` -> Ordering,
`q``:` impl Fn`(`&`T``)` -> `f64`,
`)`` ``->` `Result``<``f64`, Me`>``;`
`///` Median of absolute differences (MAD).
`fn` `mad``(``self`, `centre``:` `f64`, `quantify``:` impl Fn`(`&`T``)` -> `f64``)`` ``->` `f64``;`
`}`

## Release Notes

**Version 3.0.11** - Added method

to trait `uqmedian`

for types quantifiable to `Median`

by some closure `u64`

. Fixed a recent bug in `q`

, whereby the pivot reference was not timely saved. Sorry about that. This was affecting results where the pivot coincident with the median was guessed early on.`oddmedian_by`

**Version 3.0.10** - Added

. It is faster on u64 data than the general purpose `medianu64`

. It is using a new algorithm that partitions by bits, thus avoiding the complexities of pivot estimation.`median_by`

**Version 3.0.9** - Improved pivot estimation for large data sets.

**Version 3.0.8** - Added

module and reorganized the source.`implementation.rs`

**Version 3.0.7** - Added

, applying `medf_weighted`

weights.`&``[``f64``]`

**Version 3.0.6** - Moved

, `part`

and `ref_vec`

into crate `deref_vec`

, to allow their wider use.`Indxvec`

**Version 3.0.5** - Obsolete code pruning.

**Version 3.0.4** - Some minor code simplifications.

**Version 3.0.3** - Updated dev dependency

to 2.0.`ran`

**Version 3.0.2** - Added function

that finds median byte by superfast radix search. More primitive types to follow.`medianu8`

**Version 3.0.1** - Renamed

to `correlation`

to avoid name clashes elsewhere.`med_correlation`

**Version 3.0.0** - Numerous improvements to speed and generality and renaming.

#### Dependencies

~91KB