Skip to content

Commit f96f696

Browse files
authored
Add vector normalization to Vector trait (#114)
Signed-off-by: Markus Mayer <[email protected]>
1 parent 4548408 commit f96f696

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/float.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ impl F32 {
226226
/// Is this floating point value even?
227227
fn is_even(&self) -> bool {
228228
// any floating point value that doesn't fit in an i32 range is even,
229-
// and will loose 1's digit precision at exp values of 23+
229+
// and will lose 1's digit precision at exp values of 23+
230230
if self.extract_exponent_value() >= 31 {
231231
true
232232
} else {

src/vector.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,45 @@ where
7272
.sum::<f32>()
7373
.sqrt()
7474
}
75+
76+
/// Returns a normalized version of the vector.
77+
fn normalized(mut self) -> Self
78+
where
79+
Self: FromIterator<C>,
80+
C: Into<f32> + From<f32>,
81+
{
82+
let norm = self.magnitude();
83+
self.map(|n| C::from(n.into() / norm))
84+
}
85+
86+
/// Applies a function to each element of the vector
87+
/// and returns a new vector of the transformed elements.
88+
fn map<F>(&mut self, map: F) -> Self
89+
where
90+
F: FnMut(C) -> C,
91+
{
92+
Self::from_iter(self.iter().map(map))
93+
}
94+
}
95+
96+
#[cfg(test)]
97+
mod tests {
98+
use super::*;
99+
100+
#[test]
101+
fn normalized() {
102+
const ERROR: f32 = 1e-6;
103+
let vec = Vector3d {
104+
x: 3.0,
105+
y: 4.0,
106+
z: 5.0,
107+
};
108+
let norm = vec.magnitude();
109+
assert!((norm - 7.071068).abs() <= ERROR);
110+
111+
let normalized = vec.normalized();
112+
assert!((normalized.x - 0.42426407).abs() <= ERROR);
113+
assert!((normalized.y - 0.56568545).abs() <= ERROR);
114+
assert!((normalized.z - 0.70710677).abs() <= ERROR);
115+
}
75116
}

0 commit comments

Comments
 (0)