1 // This file is part of Eigen, a lightweight C++ template library 2 // for linear algebra. 3 // 4 // Copyright (C) 2011 Jitse Niesen <jitse (at) maths.leeds.ac.uk> 5 // 6 // This Source Code Form is subject to the terms of the Mozilla 7 // Public License v. 2.0. If a copy of the MPL was not distributed 8 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 9 10 #include "main.h" 11 #include <unsupported/Eigen/MatrixFunctions> 12 13 template <typename MatrixType, int IsComplex = NumTraits<typename internal::traits<MatrixType>::Scalar>::IsComplex> 14 struct generateTestMatrix; 15 16 // for real matrices, make sure none of the eigenvalues are negative 17 template <typename MatrixType> 18 struct generateTestMatrix<MatrixType,0> 19 { 20 static void run(MatrixType& result, typename MatrixType::Index size) 21 { 22 MatrixType mat = MatrixType::Random(size, size); 23 EigenSolver<MatrixType> es(mat); 24 typename EigenSolver<MatrixType>::EigenvalueType eivals = es.eigenvalues(); 25 for (typename MatrixType::Index i = 0; i < size; ++i) { 26 if (eivals(i).imag() == 0 && eivals(i).real() < 0) 27 eivals(i) = -eivals(i); 28 } 29 result = (es.eigenvectors() * eivals.asDiagonal() * es.eigenvectors().inverse()).real(); 30 } 31 }; 32 33 // for complex matrices, any matrix is fine 34 template <typename MatrixType> 35 struct generateTestMatrix<MatrixType,1> 36 { 37 static void run(MatrixType& result, typename MatrixType::Index size) 38 { 39 result = MatrixType::Random(size, size); 40 } 41 }; 42 43 template<typename MatrixType> 44 void testMatrixSqrt(const MatrixType& m) 45 { 46 MatrixType A; 47 generateTestMatrix<MatrixType>::run(A, m.rows()); 48 MatrixType sqrtA = A.sqrt(); 49 VERIFY_IS_APPROX(sqrtA * sqrtA, A); 50 } 51 52 void test_matrix_square_root() 53 { 54 for (int i = 0; i < g_repeat; i++) { 55 CALL_SUBTEST_1(testMatrixSqrt(Matrix3cf())); 56 CALL_SUBTEST_2(testMatrixSqrt(MatrixXcd(12,12))); 57 CALL_SUBTEST_3(testMatrixSqrt(Matrix4f())); 58 CALL_SUBTEST_4(testMatrixSqrt(Matrix<double,Dynamic,Dynamic,RowMajor>(9, 9))); 59 CALL_SUBTEST_5(testMatrixSqrt(Matrix<float,1,1>())); 60 CALL_SUBTEST_5(testMatrixSqrt(Matrix<std::complex<float>,1,1>())); 61 } 62 } 63