Merge pull request #698 from rustsim/try_set_magnitude

Add a method to set the magnitude of a vector.
This commit is contained in:
Sébastien Crozet 2020-03-02 11:35:47 +01:00
commit 155ba3a50a
1 changed files with 16 additions and 1 deletions

View File

@ -185,6 +185,21 @@ impl<N: ComplexField, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> {
self.norm_squared() self.norm_squared()
} }
/// Sets the magnitude of this vector unless it is smaller than `min_magnitude`.
///
/// If `self.magnitude()` is smaller than `min_magnitude`, it will be left unchanged.
/// Otherwise this is equivalent to: `*self = self.normalize() * magnitude.
#[inline]
pub fn try_set_magnitude(&mut self, magnitude: N::RealField, min_magnitude: N::RealField)
where S: StorageMut<N, R, C> {
let n = self.norm();
if n >= min_magnitude {
self.scale_mut(magnitude / n)
}
}
/// Returns a normalized version of this matrix. /// Returns a normalized version of this matrix.
#[inline] #[inline]
#[must_use = "Did you mean to use normalize_mut()?"] #[must_use = "Did you mean to use normalize_mut()?"]
@ -227,7 +242,7 @@ impl<N: ComplexField, R: Dim, C: Dim, S: StorageMut<N, R, C>> Matrix<N, R, C, S>
/// Normalizes this matrix in-place or does nothing if its norm is smaller or equal to `eps`. /// Normalizes this matrix in-place or does nothing if its norm is smaller or equal to `eps`.
/// ///
/// If the normalization succeeded, returns the old normal of this matrix. /// If the normalization succeeded, returns the old norm of this matrix.
#[inline] #[inline]
pub fn try_normalize_mut(&mut self, min_norm: N::RealField) -> Option<N::RealField> { pub fn try_normalize_mut(&mut self, min_norm: N::RealField) -> Option<N::RealField> {
let n = self.norm(); let n = self.norm();