tensor-0.1.0
 All Data Structures Namespaces Functions Variables Typedefs Enumerations Enumerator Groups Pages
expm_d.cc
1 // -*- mode: c++; fill-column: 80; c-basic-offset: 2; indent-tabs-mode: nil -*-
2 /*
3  Copyright (c) 2010 Juan Jose Garcia Ripoll
4 
5  Tensor is free software; you can redistribute it and/or modify it
6  under the terms of the GNU Library General Public License as published
7  by the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Library General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License along
16  with this program; if not, write to the Free Software Foundation, Inc.,
17  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 
20 #include <algorithm>
21 #include <tensor/tensor.h>
22 #include <tensor/linalg.h>
23 #include <tensor/io.h>
24 
25 namespace linalg {
26 
41  const RTensor
42  expm(const RTensor &Aunorm, unsigned int order)
43  {
44  assert(Aunorm.rank() == 2);
45  assert(Aunorm.columns() == Aunorm.rows());
46 
47  // Scale A until the norm is < 1/2
48  double val = log2(matrix_norminf(Aunorm));
49  int e = (int)floor(val);
50  size_t j = std::max((int)0, (int)(e+1));
51 
52  // Pade approximation for exp(A)
53  double c = 1.0/2;
54  RTensor A = Aunorm / exp2(j);
55  RTensor N = RTensor::eye(A.rows()) + c * A;
56  RTensor D = RTensor::eye(A.rows()) - c * A;
57  RTensor X = A;
58 
59  for (size_t k = 2; k <= order; k++) {
60  c = (c * (order-k+1)) / (k*(2*order-k+1));
61  X = mmult(A, X);
62  RTensor cX = c * X;
63  N = N + cX;
64  if ((k & 1) == 0) {
65  D = D + cX;
66  } else {
67  D = D - cX;
68  }
69  }
70  X = solve(D, N);
71  for (size_t k = 1; k <= j; k++) {
72  X = mmult(X, X);
73  }
74  return X;
75 }
76 
77 }
int rank() const
Number of Tensor indices.
Definition: tensor.h:119
index columns() const
Query the size of 2nd index.
Definition: tensor.h:137
static const Tensor< elt_t > eye(index rows)
Identity matrix.
Definition: tensor.h:231
index rows() const
Query then size of 1st index.
Definition: tensor.h:139
const RTensor expm(const RTensor &A, unsigned int order=7)
Compute the exponential of a real matrix.
Definition: expm_d.cc:42
Real Tensor with elements of type "double".
Definition: tensor.h:349
const RTensor solve(const RTensor &A, const RTensor &B)
Solve a real linear system of equations by Gauss-Seidel method.
Definition: solve_d.cc:39