You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.1 KiB

  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2011 Jitse Niesen <jitse@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. #include "main.h"
  10. #include <unsupported/Eigen/MatrixFunctions>
  11. template <typename MatrixType, int IsComplex = NumTraits<typename internal::traits<MatrixType>::Scalar>::IsComplex>
  12. struct generateTestMatrix;
  13. // for real matrices, make sure none of the eigenvalues are negative
  14. template <typename MatrixType>
  15. struct generateTestMatrix<MatrixType,0>
  16. {
  17. static void run(MatrixType& result, typename MatrixType::Index size)
  18. {
  19. MatrixType mat = MatrixType::Random(size, size);
  20. EigenSolver<MatrixType> es(mat);
  21. typename EigenSolver<MatrixType>::EigenvalueType eivals = es.eigenvalues();
  22. for (typename MatrixType::Index i = 0; i < size; ++i) {
  23. if (eivals(i).imag() == 0 && eivals(i).real() < 0)
  24. eivals(i) = -eivals(i);
  25. }
  26. result = (es.eigenvectors() * eivals.asDiagonal() * es.eigenvectors().inverse()).real();
  27. }
  28. };
  29. // for complex matrices, any matrix is fine
  30. template <typename MatrixType>
  31. struct generateTestMatrix<MatrixType,1>
  32. {
  33. static void run(MatrixType& result, typename MatrixType::Index size)
  34. {
  35. result = MatrixType::Random(size, size);
  36. }
  37. };
  38. template<typename MatrixType>
  39. void testMatrixSqrt(const MatrixType& m)
  40. {
  41. MatrixType A;
  42. generateTestMatrix<MatrixType>::run(A, m.rows());
  43. MatrixType sqrtA = A.sqrt();
  44. VERIFY_IS_APPROX(sqrtA * sqrtA, A);
  45. }
  46. void test_matrix_square_root()
  47. {
  48. for (int i = 0; i < g_repeat; i++) {
  49. CALL_SUBTEST_1(testMatrixSqrt(Matrix3cf()));
  50. CALL_SUBTEST_2(testMatrixSqrt(MatrixXcd(12,12)));
  51. CALL_SUBTEST_3(testMatrixSqrt(Matrix4f()));
  52. CALL_SUBTEST_4(testMatrixSqrt(Matrix<double,Dynamic,Dynamic,RowMajor>(9, 9)));
  53. CALL_SUBTEST_5(testMatrixSqrt(Matrix<float,1,1>()));
  54. CALL_SUBTEST_5(testMatrixSqrt(Matrix<std::complex<float>,1,1>()));
  55. }
  56. }