Skip to content

Commit 2760974

Browse files
committed
add correct floating point min and max methods.
The `std::cmp` functions are not correct for floating point types. `min(NaN, 2.0)` and `min(2.0, NaN)` return different values, because these functions assume a total order. Floating point types need special `min`, `max` and `clamp` functions.
1 parent 6e7f170 commit 2760974

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

src/libstd/num/f32.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
// except according to those terms.
1010

1111
//! Operations and constants for 32-bits floats (`f32` type)
12+
1213
#[allow(missing_doc)];
1314

1415
use prelude::*;
@@ -311,6 +312,16 @@ impl Bounded for f32 {
311312
impl Primitive for f32 {}
312313

313314
impl Float for f32 {
315+
#[inline]
316+
fn max(self, other: f32) -> f32 {
317+
unsafe { cmath::c_float::fmax(self, other) }
318+
}
319+
320+
#[inline]
321+
fn min(self, other: f32) -> f32 {
322+
unsafe { cmath::c_float::fmin(self, other) }
323+
}
324+
314325
#[inline]
315326
fn nan() -> f32 { 0.0 / 0.0 }
316327

src/libstd/num/f64.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ use num::{Zero, One, Bounded, strconv};
2323
use num;
2424
use intrinsics;
2525

26-
pub use cmp::{min, max};
27-
2826
macro_rules! delegate(
2927
(
3028
$(
@@ -313,6 +311,16 @@ impl Bounded for f64 {
313311
impl Primitive for f64 {}
314312

315313
impl Float for f64 {
314+
#[inline]
315+
fn max(self, other: f64) -> f64 {
316+
unsafe { cmath::c_double::fmax(self, other) }
317+
}
318+
319+
#[inline]
320+
fn min(self, other: f64) -> f64 {
321+
unsafe { cmath::c_double::fmin(self, other) }
322+
}
323+
316324
#[inline]
317325
fn nan() -> f64 { 0.0 / 0.0 }
318326

src/libstd/num/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,9 @@ pub enum FPCategory {
313313
pub trait Float: Signed
314314
+ Round
315315
+ Primitive {
316+
fn max(self, other: Self) -> Self;
317+
fn min(self, other: Self) -> Self;
318+
316319
// FIXME (#5527): These should be associated constants
317320
fn nan() -> Self;
318321
fn infinity() -> Self;

src/libtest/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1063,7 +1063,7 @@ impl MetricMap {
10631063
Some(v) => {
10641064
let delta = v.value - vold.value;
10651065
let noise = match noise_pct {
1066-
None => f64::max(vold.noise.abs(), v.noise.abs()),
1066+
None => vold.noise.abs().max(v.noise.abs()),
10671067
Some(pct) => vold.value * pct / 100.0
10681068
};
10691069
if delta.abs() <= noise {

0 commit comments

Comments
 (0)