Skip to main content

embedded_maths/embedded-maths-functions/
floor.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! `f32` floor operations.
3
4/// Returns the largest integer less than or equal to `x`.
5#[inline(always)]
6pub fn floor(x: f32) -> f32 {
7    if x.is_nan() || x.is_infinite() {
8        return x;
9    }
10    let integer = super::trunc::trunc(x);
11    if x == integer || x == 0.0 {
12        integer
13    } else if x < 0.0 {
14        integer - 1.0
15    } else {
16        integer
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::floor;
23
24    #[test]
25    fn positive_negative_and_special_values() {
26        assert_eq!(floor(1.2), 1.0);
27        assert_eq!(floor(-1.2), -2.0);
28        assert_eq!(floor(-3.0), -3.0);
29        assert_eq!(floor(f32::NEG_INFINITY), f32::NEG_INFINITY);
30        assert!(floor(f32::NAN).is_nan());
31    }
32}