Overflow-safe integer midpoint with rounding control
Draft because I am not sold on the free-function spelling midpoint(a, b). It is desirable by symmetry with min(a, b) and max(a, b), and because it correctly captures that this is a commutative operation; neither operand is privileged. But Swift generally eschews free functions. This could equally be a static member (Int.midpoint(a, b)), or possibly use some other spelling.
Declaration:
public func midpoint<T: BinaryInteger>(
_ a: T,
_ b: T,
rounding rule: RoundingRule = .down
) -> T
Usage:
let dn = midpoint(start, end)
let up = midpoint(start, end, rounding: .up)
Unlike commonly seen expressions such as (a+b)/2 or (a+b) >> 1 or a + (b-a)/2 (all of which may overflow for fixed-width integers), this function never overflows, and the result is guaranteed to be representable in the result type.
The default rounding rule is .down, which matches the behavior of (a + b) >> 1 when that expression does not overflow. Rounding .towardZero matches the behavior of (a + b)/2 when that expression does not overflow. All other rounding modes are supported.
Overflow-safe integer midpoint with rounding control
Draft because I am not sold on the free-function spelling
midpoint(a, b)
. It is desirable by symmetry withmin(a, b)
andmax(a, b)
, and because it correctly captures that this is a commutative operation; neither operand is privileged. But Swift generally eschews free functions. This could equally be a static member (Int.midpoint(a, b)
), or possibly use some other spelling.Declaration:
Usage:
Unlike commonly seen expressions such as
(a+b)/2
or(a+b) >> 1
ora + (b-a)/2
(all of which may overflow for fixed-width integers), this function never overflows, and the result is guaranteed to be representable in the result type.The default rounding rule is
.down
, which matches the behavior of(a + b) >> 1
when that expression does not overflow. Rounding.towardZero
matches the behavior of(a + b)/2
when that expression does not overflow. All other rounding modes are supported.