Skip to content

Commit

Permalink
Merge pull request #698 from rustsim/try_set_magnitude
Browse files Browse the repository at this point in the history
Add a method to set the magnitude of a vector.
  • Loading branch information
sebcrozet committed Mar 2, 2020
2 parents 1d64de3 + b09d977 commit 155ba3a
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/base/norm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,21 @@ impl<N: ComplexField, R: Dim, C: Dim, S: Storage<N, R, C>> Matrix<N, R, C, S> {
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.
#[inline]
#[must_use = "Did you mean to use normalize_mut()?"]
Expand Down Expand Up @@ -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`.
///
/// If the normalization succeeded, returns the old normal of this matrix.
/// If the normalization succeeded, returns the old norm of this matrix.
#[inline]
pub fn try_normalize_mut(&mut self, min_norm: N::RealField) -> Option<N::RealField> {
let n = self.norm();
Expand Down

0 comments on commit 155ba3a

Please sign in to comment.