Added pow function.

I'll try adding some unchecked and in place variants soon.
This commit is contained in:
Violeta Hernández 2021-04-05 12:17:49 -05:00
parent f8173bd668
commit ab85766b5a
2 changed files with 54 additions and 0 deletions

View File

@ -19,6 +19,7 @@ pub mod householder;
mod inverse;
mod lu;
mod permutation_sequence;
mod pow;
mod qr;
mod schur;
mod solve;
@ -41,6 +42,7 @@ pub use self::full_piv_lu::*;
pub use self::hessenberg::*;
pub use self::lu::*;
pub use self::permutation_sequence::*;
pub use self::pow::*;
pub use self::qr::*;
pub use self::schur::*;
pub use self::svd::*;

52
src/linalg/pow.rs Normal file
View File

@ -0,0 +1,52 @@
//! This module provides the matrix exponential (pow) function to square matrices.
use std::ops::DivAssign;
use crate::{allocator::Allocator, DefaultAllocator, DimMin, DimMinimum, MatrixN};
use num::PrimInt;
use simba::scalar::ComplexField;
impl<N: ComplexField, D> MatrixN<N, D>
where
D: DimMin<D, Output = 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.
/// Returns `None` only when the matrix is non-invertible and raised to a
/// negative power.
pub fn pow<T: PrimInt + DivAssign>(&self, mut e: T) -> Option<Self> {
let zero = T::zero();
if e == zero {
let mut i = self.clone();
i.fill_with_identity();
return Some(i);
}
let mut acc;
if e < zero {
acc = self.clone().try_inverse()?;
} else {
acc = self.clone();
}
let one = T::one();
let two = T::from(2u8).unwrap();
let mut multiplier = acc.clone();
while e != zero {
if e % two == one {
acc *= &multiplier;
}
e /= two;
multiplier *= multiplier.clone();
}
Some(acc)
}
}