# Median

- Status:
**Pitch** - Implementation: apple/swift#39335

## Introduction

This proposal would add global `median`

functions to the standard library.

## Motivation

A comparable value can be clamped to a closed range, by combining the existing `min`

and `max`

functions.

```
// Values clamped to `0.0...1.0`
max(0.0, min(-.pi, 1.0)) //-> 0.0
max(0.0, min(+.pi, 1.0)) //-> 1.0
```

## Proposed solution

The previous example can be expressed more easily as:

```
// Values clamped to `0.0...1.0`
median(0.0, -.pi, 1.0) //-> 0.0
median(0.0, +.pi, 1.0) //-> 1.0
```

## Detailed design

```
public func median<T: Comparable> (_ x: T, _ y: T, _ z: T) -> T
public func median<T: FloatingPoint>(_ x: T, _ y: T, _ z: T) -> T
public func median<T: FloatingPoint>(_ x: T, _ y: T, _ rest: T...) -> T
```

- The functions without a variadic parameter are optimized for clamping.
- The values can be given in any order, and will be sorted in ascending order.
- Floating-point values, including signed zeros and NaNs, will be totally ordered.
- The middle value, or the arithmetic mean of two middle values, will be returned.

```
median(1.0, 2.0) //-> 1.5
median(1.0, 2.0, 4.0) //-> 2.0
median(1.0, 2.0, 4.0, 8.0) //-> 3.0
median(1.0, 2.0, 4.0, 8.0, 16.0) //-> 4.0
```

## Acknowledgments

The idea for this proposal was suggested by Steve Canon.