numeric_statistics/f64/min.rs
1/// Calculate statistical min for values.
2///
3/// # Nan
4///
5/// Return NaN if the values are empty.
6///
7/// From <https://doc.rust-lang.org/std/primitive.f64.html#method.max>:
8///
9/// If one of the arguments is NaN, then the other argument is returned. This
10/// follows the IEEE 754-2008 semantics for minNum, except for handling of
11/// signaling NaNs; this function handles all NaNs the same way and avoids
12/// minNum’s problems with associativity. This also matches the behavior of
13/// libm’s fmin. In particular, if the inputs compare equal (such as for the case
14/// of +0.0 and -0.0), either input may be returned non-deterministically.
15///
16/// # Example
17///
18/// ```rust
19/// #[macro_use]
20/// use numeric_statistics::f64::min::*;
21/// let values = &[1.0, 2.0, 4.0];
22/// let min = min(values);
23/// assert_eq!(min, 1.0);
24/// ```
25///
26pub fn min<T: AsRef<[f64]>>(values: T) -> f64 {
27 let values = values.as_ref();
28 if values.is_empty() { return f64::NAN; }
29 values.iter().fold(f64::NAN, |a, x| f64::min(a, *x))
30}
31
32#[cfg(test)]
33mod test {
34 use super::*;
35
36 #[test]
37 fn test_empty() {
38 let x: &[f64] = &[];
39 assert!(min(x).is_nan());
40 }
41
42 #[test]
43 fn test_nan() {
44 let x: &[f64] = &[f64::NAN];
45 assert!(min(x).is_nan());
46 }
47
48 #[test]
49 fn test_value() {
50 let x: &[f64] = &[1.0];
51 assert_eq!(min(x), 1.0);
52 }
53
54 #[test]
55 fn test_values_ascending() {
56 let x = &[1.0, 2.0, 3.0];
57 assert_eq!(min(x), 1.0);
58 }
59
60 #[test]
61 fn test_values_ascending_and_nans() {
62 let x = &[1.0, f64::NAN, 2.0, f64::NAN, 3.0];
63 assert_eq!(min(x), 1.0);
64 }
65
66 #[test]
67 fn test_values_descending() {
68 let x = &[3.0, 2.0, 1.0];
69 assert_eq!(min(x), 1.0);
70 }
71
72 #[test]
73 fn test_values_descending_and_nans() {
74 let x = &[3.0, f64::NAN, 2.0, f64::NAN, 1.0];
75 assert_eq!(min(x), 1.0);
76 }
77
78}