Skip to content

Commit

Permalink
Add vector normalization to Vector trait
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsided committed Jul 31, 2024
1 parent 83ce0ac commit c0e2cde
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,37 @@ where
.sum::<f32>()
.sqrt()
}

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

#[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);
}
}

0 comments on commit c0e2cde

Please sign in to comment.