Skip to content

Commit

Permalink
Add magnitude_sq function to support non-f32
Browse files Browse the repository at this point in the history
Signed-off-by: Markus Mayer <[email protected]>
  • Loading branch information
sunsided committed Jul 31, 2024
1 parent 4548408 commit 123f5ef
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl F32 {
/// Is this floating point value even?
fn is_even(&self) -> bool {
// any floating point value that doesn't fit in an i32 range is even,
// and will loose 1's digit precision at exp values of 23+
// and will lose 1's digit precision at exp values of 23+
if self.extract_exponent_value() >= 31 {
true
} else {
Expand Down
24 changes: 24 additions & 0 deletions src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ where
differences.map(|n| n * n).sum::<f32>().sqrt()
}

/// Compute the squared magnitude of a vector
fn magnitude_sq(self) -> C
where
C: core::iter::Sum,
{
self.iter().map(|n| n * n).sum()
}

/// Compute the magnitude of a vector
fn magnitude(self) -> f32
where
Expand All @@ -73,3 +81,19 @@ where
.sqrt()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn magnitude_sq() {
let vec = Vector3d {
x: 3.0,
y: 4.0,
z: 5.0,
};
let mag = vec.magnitude_sq();
assert_eq!(mag, 3.0 * 3.0 + 4.0 * 4.0 + 5.0 * 5.0);
}
}

0 comments on commit 123f5ef

Please sign in to comment.