Skip to main content

embedded_maths/embedded-maths-functions/
sqrt.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Square root of `f32` for `no_std`, powered by `embedded-f32-sqrt`.
3//!
4//! This module calls [`embedded_f32_sqrt::sqrt`] rather than relying on
5//! `micromath` or floating-point methods that require `std`. It uses
6//! IEEE 754 bit manipulation and Newton-Raphson iterations and is suitable
7//! for embedded targets with or without an FPU.
8//!
9//! # Behavior
10//!
11//! | Input | Result |
12//! |-------|--------|
13//! | `>= 0.0` | `Ok(square_root)` |
14//! | `-0.0` | `Ok(-0.0)` |
15//! | Negative value | `Err(NegativeInput)` |
16//! | `NaN` | `Ok(NaN)` |
17//! | `+Infinity` | `Ok(+Infinity)` |
18
19pub use embedded_f32_sqrt::NegativeInput;
20
21use embedded_f32_sqrt::sqrt as embedded_sqrt;
22
23/// Computes the square root of `x`.
24///
25/// Calls [`embedded_f32_sqrt::sqrt`] for the implementation and preserves the
26/// sign of negative zero.
27pub fn sqrt(x: f32) -> Result<f32, NegativeInput> {
28    if x.to_bits() == (-0.0f32).to_bits() {
29        return Ok(-0.0);
30    }
31
32    embedded_sqrt(x)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn perfect_squares() {
41        for &(value, expected) in &[(0.0, 0.0), (1.0, 1.0), (4.0, 2.0), (9.0, 3.0), (25.0, 5.0)] {
42            assert_eq!(sqrt(value).unwrap(), expected);
43        }
44    }
45
46    #[test]
47    fn irrational_values() {
48        let result = sqrt(2.0).unwrap();
49        assert!((result as f64 - (2.0f64).sqrt()).abs() <= 1e-6);
50    }
51
52    #[test]
53    fn negative_input() {
54        assert_eq!(sqrt(-1.0), Err(NegativeInput));
55    }
56
57    #[test]
58    fn zero_sign_and_special_values() {
59        assert_eq!(sqrt(-0.0).unwrap().to_bits(), (-0.0f32).to_bits());
60        assert!(sqrt(f32::NAN).unwrap().is_nan());
61        assert_eq!(sqrt(f32::INFINITY).unwrap(), f32::INFINITY);
62    }
63}