Skip to content
Open
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
38 changes: 38 additions & 0 deletions src/structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@ where
}

/// Returns a vector with the same direction, but with a magnitude of `1`.
///
/// If a vector with magnitude zero is passed in this will return a `NaN` vector. If you do not
/// want this then use `InnerSpace::checked_normalize` instead.
#[inline]
fn normalize(self) -> Self
where
Expand All @@ -282,13 +285,48 @@ where
}

/// Returns a vector with the same direction and a given magnitude.
///
/// If a vector with magnitude zero is passed in this will return a `NaN` vector. If you do not
/// want this then use `InnerSpace::checked_normalize_to` instead.
#[inline]
fn normalize_to(self, magnitude: Self::Scalar) -> Self
where
Self::Scalar: Float,
{
self * (magnitude / self.magnitude())
}

/// Returns a vector with the same direction, but with a magnitude of `1` unless the vector is
/// zero in which case it will return zero.
///
/// Same as `InnerSpace::normalize` except when `Zero::is_zero` is true.
#[inline]
fn checked_normalize(self) -> Self
where
Self::Scalar: Float,
{
if self.is_zero() {
self
} else {
self.normalize()
}
}

/// Returns a vector with the same direction and a given magnitude unless the vector is
/// zero in which case it will return zero.
///
/// Same as `InnerSpace::normalize_to` except when `Zero::is_zero` is true.
#[inline]
fn checked_normalize_to(self, magnitude: Self::Scalar) -> Self
where
Self::Scalar: Float,
{
if self.is_zero() {
self
} else {
self.normalize_to(magnitude)
}
}
}

/// Points in a [Euclidean space](https://en.wikipedia.org/wiki/Euclidean_space)
Expand Down
28 changes: 28 additions & 0 deletions tests/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,34 @@ fn test_normalize() {
);
}

#[test]
fn test_checked_normalize() {
assert_ulps_eq!(
Vector2::new(0.0f64, 0.0f64).checked_normalize(),
Vector2::new(0.0f64, 0.0f64)
);
assert_ulps_eq!(
Vector3::new(0.0f64, 0.0f64, 0.0f64).checked_normalize(),
Vector3::new(0.0f64, 0.0f64, 0.0f64)
);
assert_ulps_eq!(
Vector4::new(0.0f64, 0.0f64, 0.0f64, 0.0f64).checked_normalize(),
Vector4::new(0.0f64, 0.0f64, 0.0f64, 0.0f64)
);
assert_ulps_eq!(
Vector2::new(5.0f64, 12.0f64).checked_normalize(),
Vector2::new(5.0 / 13.0, 12.0 / 13.0)
);
assert_ulps_eq!(
Vector3::new(4.0f64, 4.0f64, 7.0f64).checked_normalize(),
Vector3::new(4.0 / 9.0, 4.0 / 9.0, 7.0 / 9.0)
);
assert_ulps_eq!(
Vector4::new(1.0f64, 3.0f64, 5.0f64, 17.0f64).checked_normalize(),
Vector4::new(1.0 / 18.0, 3.0 / 18.0, 5.0 / 18.0, 17.0 / 18.0)
);
}

#[test]
fn test_project_on() {
assert_ulps_eq!(
Expand Down