Skip to content

Commit 91344f0

Browse files
committed
Add unit test for const sqrt function
1 parent 9a57d43 commit 91344f0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

swiftnav/src/math.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,19 @@ pub(crate) const fn compile_time_max_u16(a: u16, b: u16) -> u16 {
2929
///
3030
/// # Panics
3131
///
32+
/// - This function will panic if the given number is NOT between 0.0 and 1.0.
3233
/// - This function will panic if the computation does not converge within 100 iterations.
3334
///
3435
/// # Notes
3536
///
3637
/// - This function is marked as `const`, allowing it to be evaluated at compile time.
3738
/// - The algorithm iteratively refines the approximation of the square root until the result stabilizes.
3839
pub(crate) const fn compile_time_sqrt(s: f64) -> f64 {
40+
assert!(
41+
s >= 0.0 && s <= 1.0,
42+
"Can only compute square root of numbers between 0 and 1"
43+
);
44+
3945
let mut x = s;
4046
let mut y = 0.0;
4147
let mut z;
@@ -72,3 +78,22 @@ pub(crate) fn ecef2ned_matrix(llh: crate::coords::LLHRadians) -> nalgebra::Matri
7278
-sin_lat,
7379
)
7480
}
81+
82+
#[cfg(test)]
83+
mod tests {
84+
use super::*;
85+
use float_eq::assert_float_eq;
86+
use proptest::prelude::*;
87+
88+
proptest! {
89+
#![proptest_config(ProptestConfig::with_cases(1000))]
90+
91+
/// Property: Converting LLH->ECEF->LLH should always result in the original value
92+
#[test]
93+
fn newton_sqrt(x in 0.0..=1.0) {
94+
let newton_approx = compile_time_sqrt(x);
95+
let sqrt = x.sqrt();
96+
assert_float_eq!(sqrt, newton_approx, ulps <= 1, "Newton approximation of square root doesn't match IEEE sqrt! (Newton: {}, IEEE: {})", newton_approx, sqrt);
97+
}
98+
}
99+
}

0 commit comments

Comments
 (0)