2021-04-06 01:17:49 +08:00
|
|
|
//! This module provides the matrix exponential (pow) function to square matrices.
|
|
|
|
|
|
|
|
use std::ops::DivAssign;
|
|
|
|
|
2021-04-06 01:32:12 +08:00
|
|
|
use crate::{allocator::Allocator, DefaultAllocator, DimMin, MatrixN};
|
2021-04-06 01:17:49 +08:00
|
|
|
use num::PrimInt;
|
|
|
|
use simba::scalar::ComplexField;
|
|
|
|
|
|
|
|
impl<N: ComplexField, D> MatrixN<N, D>
|
|
|
|
where
|
|
|
|
D: DimMin<D, Output = D>,
|
2021-04-06 01:32:12 +08:00
|
|
|
DefaultAllocator: Allocator<N, D, D>,
|
2021-04-06 01:17:49 +08:00
|
|
|
{
|
2021-04-06 01:32:12 +08:00
|
|
|
/// Attempts to raise this matrix to an integer power in-place. Returns
|
|
|
|
/// `false` and leaves `self` untouched if the power is negative and the
|
|
|
|
/// matrix is non-invertible.
|
|
|
|
pub fn pow_mut<T: PrimInt + DivAssign>(&mut self, mut e: T) -> bool {
|
2021-04-06 01:17:49 +08:00
|
|
|
let zero = T::zero();
|
|
|
|
|
|
|
|
if e == zero {
|
2021-04-06 01:32:12 +08:00
|
|
|
self.fill_with_identity();
|
|
|
|
return true;
|
2021-04-06 01:17:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if e < zero {
|
2021-04-06 01:32:12 +08:00
|
|
|
if !self.try_inverse_mut() {
|
|
|
|
return false;
|
|
|
|
}
|
2021-04-06 01:17:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
let one = T::one();
|
|
|
|
let two = T::from(2u8).unwrap();
|
2021-04-06 01:32:12 +08:00
|
|
|
let mut multiplier = self.clone();
|
2021-04-06 01:17:49 +08:00
|
|
|
|
|
|
|
while e != zero {
|
|
|
|
if e % two == one {
|
2021-04-06 01:32:12 +08:00
|
|
|
*self *= &multiplier;
|
2021-04-06 01:17:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
e /= two;
|
|
|
|
multiplier *= multiplier.clone();
|
|
|
|
}
|
|
|
|
|
2021-04-06 01:32:12 +08:00
|
|
|
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
|
|
|
|
}
|
2021-04-06 01:17:49 +08:00
|
|
|
}
|
|
|
|
}
|