apple / swift-numerics

Advanced mathematical types and functions for Swift
Apache License 2.0
1.66k stars 140 forks source link

Integer midpoint #293

Open stephentyrone opened 2 weeks ago

stephentyrone commented 2 weeks ago

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.

stephentyrone commented 2 weeks ago

@swift-ci test

glessard commented 2 weeks ago

@swift-ci please test