tensor-0.1.0
 All Data Structures Namespaces Functions Variables Typedefs Enumerations Enumerator Groups Pages
eig_power.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 <tensor/tensor.h>
21 #include <tensor/tensor_lapack.h>
22 #include <tensor/linalg.h>
23 
24 namespace linalg {
25 
26  using namespace tensor;
27 
28  template<typename elt_t>
29  elt_t eig_power_loop(const Tensor<elt_t> &O, Tensor<elt_t> *vector,
30  bool right, size_t iter, double tol)
31  {
32  if (O.columns() != O.rows()) {
33  std::cerr << "eig_right_power cannot solve non-square problems";
34  abort();
35  }
36  if (iter == 0) {
37  iter = 20;
38  }
39  if (tol <= 0) {
40  tol = 1e-11;
41  }
42  Tensor<elt_t> v(O.columns()), old_v;
43  v.randomize();
44  v = v / norm2(v);
45  elt_t eig, old_eig;
46  for (size_t i = 0; i <= iter; i++) {
47  Tensor<elt_t> v_new = fold(O, right? -1 : 0, v, 0);
48  double n = norm2(v_new);
49  v = v_new / n;
50  eig = scprod(v_new, v);
51  if (i) {
52  double eig_change = abs(eig - old_eig);
53  if (eig_change < tol * abs(eig)) {
54  double vec_change = norm2(v - old_v);
55  if (vec_change < tol) {
56  break;
57  }
58  }
59  }
60  old_eig = eig;
61  old_v = v;
62  }
63  *vector = v;
64  return eig;
65  }
66 
67 } // namespace linalg
void randomize()
Fills with random numbers.
const CTensor eig(const RTensor &A, CTensor *R=0, CTensor *L=0)
Eigenvalue decomposition of a real matrix.
Definition: eig_d.cc:45
index columns() const
Query the size of 2nd index.
Definition: tensor.h:137
index rows() const
Query then size of 1st index.
Definition: tensor.h:139