Added pow_mut.

Actually, I think this will do.
This commit is contained in:
Violeta Hernández 2021-04-05 12:32:12 -05:00
parent ab85766b5a
commit 06b657ad49
1 changed files with 26 additions and 20 deletions

View File

@ -2,51 +2,57 @@
use std::ops::DivAssign; use std::ops::DivAssign;
use crate::{allocator::Allocator, DefaultAllocator, DimMin, DimMinimum, MatrixN}; use crate::{allocator::Allocator, DefaultAllocator, DimMin, MatrixN};
use num::PrimInt; use num::PrimInt;
use simba::scalar::ComplexField; use simba::scalar::ComplexField;
impl<N: ComplexField, D> MatrixN<N, D> impl<N: ComplexField, D> MatrixN<N, D>
where where
D: DimMin<D, Output = D>, D: DimMin<D, Output = D>,
DefaultAllocator: Allocator<N, D, D> DefaultAllocator: Allocator<N, D, D>,
+ Allocator<(usize, usize), DimMinimum<D, D>>
+ Allocator<N, D>
+ Allocator<N::RealField, D>
+ Allocator<N::RealField, D, D>,
{ {
/// Raises a matrix to an integer power using exponentiation by squares. /// Attempts to raise this matrix to an integer power in-place. Returns
/// Returns `None` only when the matrix is non-invertible and raised to a /// `false` and leaves `self` untouched if the power is negative and the
/// negative power. /// matrix is non-invertible.
pub fn pow<T: PrimInt + DivAssign>(&self, mut e: T) -> Option<Self> { pub fn pow_mut<T: PrimInt + DivAssign>(&mut self, mut e: T) -> bool {
let zero = T::zero(); let zero = T::zero();
if e == zero { if e == zero {
let mut i = self.clone(); self.fill_with_identity();
i.fill_with_identity(); return true;
return Some(i);
} }
let mut acc;
if e < zero { if e < zero {
acc = self.clone().try_inverse()?; if !self.try_inverse_mut() {
} else { return false;
acc = self.clone(); }
} }
let one = T::one(); let one = T::one();
let two = T::from(2u8).unwrap(); let two = T::from(2u8).unwrap();
let mut multiplier = acc.clone(); let mut multiplier = self.clone();
while e != zero { while e != zero {
if e % two == one { if e % two == one {
acc *= &multiplier; *self *= &multiplier;
} }
e /= two; e /= two;
multiplier *= multiplier.clone(); multiplier *= multiplier.clone();
} }
Some(acc) true
}
/// Raise this matrix to an integer power. Returns `None` only if the power
/// is negative and the matrix is non-invertible.
pub fn pow<T: PrimInt + DivAssign>(&self, e: T) -> Option<Self> {
let mut clone = self.clone();
if clone.pow_mut(e) {
Some(clone)
} else {
None
}
} }
} }