numeric_statistics/f32/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.f32.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/// use numeric_statistics::f64::min::*;
20/// let values = &[1.0, 2.0, 4.0];
21/// let min = min(values);
22/// assert_eq!(min, 1.0);
23/// ```
24///
25pub fn min<T: AsRef<[f32]>>(values: T) -> f32 {
26 let values = values.as_ref();
27 if values.is_empty() { return f32::NAN; }
28 values.iter().fold(f32::NAN, |a, x| f32::min(a, *x))
29}
30
31#[cfg(test)]
32mod test {
33 use super::*;
34
35 #[test]
36 fn test_empty() {
37 let x: &[f32] = &[];
38 assert!(min(x).is_nan());
39 }
40
41 #[test]
42 fn test_nan() {
43 let x: &[f32] = &[f32::NAN];
44 assert!(min(x).is_nan());
45 }
46
47 #[test]
48 fn test_value() {
49 let x: &[f32] = &[1.0];
50 assert_eq!(min(x), 1.0);
51 }
52
53 #[test]
54 fn test_values_ascending() {
55 let x = &[1.0, 2.0, 3.0];
56 assert_eq!(min(x), 1.0);
57 }
58
59 #[test]
60 fn test_values_ascending_and_nans() {
61 let x = &[1.0, f32::NAN, 2.0, f32::NAN, 3.0];
62 assert_eq!(min(x), 1.0);
63 }
64
65 #[test]
66 fn test_values_descending() {
67 let x = &[3.0, 2.0, 1.0];
68 assert_eq!(min(x), 1.0);
69 }
70
71 #[test]
72 fn test_values_descending_and_nans() {
73 let x = &[3.0, f32::NAN, 2.0, f32::NAN, 1.0];
74 assert_eq!(min(x), 1.0);
75 }
76
77}