Implement midpoint for all floating point f32 and f64
This commit is contained in:
parent
1a72d7c7c4
commit
bf73234d92
3 changed files with 125 additions and 3 deletions
|
@ -940,6 +940,42 @@ impl f32 {
|
|||
}
|
||||
}
|
||||
|
||||
/// Calculates the middle point of `self` and `rhs`.
|
||||
///
|
||||
/// This returns NaN when *either* argument is NaN or if a combination of
|
||||
/// +inf and -inf is provided as arguments.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(num_midpoint)]
|
||||
/// assert_eq!(1f32.midpoint(4.0), 2.5);
|
||||
/// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
|
||||
/// ```
|
||||
#[unstable(feature = "num_midpoint", issue = "110840")]
|
||||
pub fn midpoint(self, other: f32) -> f32 {
|
||||
const LO: f32 = f32::MIN_POSITIVE * 2.;
|
||||
const HI: f32 = f32::MAX / 2.;
|
||||
|
||||
let (a, b) = (self, other);
|
||||
let abs_a = a.abs_private();
|
||||
let abs_b = b.abs_private();
|
||||
|
||||
if abs_a <= HI && abs_b <= HI {
|
||||
// Overflow is impossible
|
||||
(a + b) / 2.
|
||||
} else if abs_a < LO {
|
||||
// Not safe to halve a
|
||||
a + (b / 2.)
|
||||
} else if abs_b < LO {
|
||||
// Not safe to halve b
|
||||
(a / 2.) + b
|
||||
} else {
|
||||
// Not safe to halve a and b
|
||||
(a / 2.) + (b / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rounds toward zero and converts to any primitive integer type,
|
||||
/// assuming that the value is finite and fits in that type.
|
||||
///
|
||||
|
|
|
@ -951,6 +951,42 @@ impl f64 {
|
|||
}
|
||||
}
|
||||
|
||||
/// Calculates the middle point of `self` and `rhs`.
|
||||
///
|
||||
/// This returns NaN when *either* argument is NaN or if a combination of
|
||||
/// +inf and -inf is provided as arguments.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(num_midpoint)]
|
||||
/// assert_eq!(1f64.midpoint(4.0), 2.5);
|
||||
/// assert_eq!((-5.5f64).midpoint(8.0), 1.25);
|
||||
/// ```
|
||||
#[unstable(feature = "num_midpoint", issue = "110840")]
|
||||
pub fn midpoint(self, other: f64) -> f64 {
|
||||
const LO: f64 = f64::MIN_POSITIVE * 2.;
|
||||
const HI: f64 = f64::MAX / 2.;
|
||||
|
||||
let (a, b) = (self, other);
|
||||
let abs_a = a.abs_private();
|
||||
let abs_b = b.abs_private();
|
||||
|
||||
if abs_a <= HI && abs_b <= HI {
|
||||
// Overflow is impossible
|
||||
(a + b) / 2.
|
||||
} else if abs_a < LO {
|
||||
// Not safe to halve a
|
||||
a + (b / 2.)
|
||||
} else if abs_b < LO {
|
||||
// Not safe to halve b
|
||||
(a / 2.) + b
|
||||
} else {
|
||||
// Not safe to halve a and b
|
||||
(a / 2.) + (b / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Rounds toward zero and converts to any primitive integer type,
|
||||
/// assuming that the value is finite and fits in that type.
|
||||
///
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue