midpoint<T extends num> function
- T a,
- T b
Finds the midpoint of two numbers (a + b) / 2 safely without overflow.
Corresponds to std::midpoint from C++20.
Properly handles the rounding direction and correctly differentiates between integer
truncation and floating point division.
Implementation
T midpoint<T extends num>(T a, T b) {
if (a is int && b is int) {
// Integer overflow safe midpoint
if ((a < 0) == (b < 0)) {
// Same sign
if (a <= b) {
return (a + ((b - a) ~/ 2)) as T;
} else {
return (a - ((a - b) ~/ 2)) as T;
}
} else {
// Differing signs cannot overflow addition
return ((a + b) ~/ 2) as T;
}
} else {
// Floating point math. Subtraction reduces precision loss compared to (a+b)/2
return (a + (b - a) / 2.0) as T;
}
}