Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add vector normalization to Vector trait #114

Merged
merged 3 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
41 changes: 41 additions & 0 deletions src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,45 @@ where
.sum::<f32>()
.sqrt()
}

/// Returns a normalized version of the vector.
fn normalized(mut self) -> Self
where
Self: FromIterator<C>,
C: Into<f32> + From<f32>,
{
let norm = self.magnitude();
self.map(|n| C::from(n.into() / norm))
}

/// Applies a function to each element of the vector
/// and returns a new vector of the transformed elements.
fn map<F>(&mut self, map: F) -> Self
where
F: FnMut(C) -> C,
{
Self::from_iter(self.iter().map(map))
}
}

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

#[test]
fn normalized() {
const ERROR: f32 = 1e-6;
let vec = Vector3d {
x: 3.0,
y: 4.0,
z: 5.0,
};
let norm = vec.magnitude();
assert!((norm - 7.071068).abs() <= ERROR);

let normalized = vec.normalized();
assert!((normalized.x - 0.42426407).abs() <= ERROR);
assert!((normalized.y - 0.56568545).abs() <= ERROR);
assert!((normalized.z - 0.70710677).abs() <= ERROR);
}
}
Loading