QuantLib: a free/open-source library for quantitative finance
Fully annotated sources - version 1.32
Loading...
Searching...
No Matches
moorepenroseinverse.hpp
1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2016 Peter Caspers
5
6 This file is part of QuantLib, a free-software/open-source library
7 for financial quantitative analysts and developers - http://quantlib.org/
8
9 QuantLib is free software: you can redistribute it and/or modify it
10 under the terms of the QuantLib license. You should have received a
11 copy of the license along with this program; if not, please email
12 <quantlib-dev@lists.sf.net>. The license is also available online at
13 <http://quantlib.org/license.shtml>.
14
15 This program is distributed in the hope that it will be useful, but WITHOUT
16 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 FOR A PARTICULAR PURPOSE. See the license for more details.
18*/
19
24#ifndef quantlib_moore_penrose_inverse
25#define quantlib_moore_penrose_inverse
26
27#include <ql/math/matrixutilities/svd.hpp>
28
29namespace QuantLib {
30
36 const Real tol = Null<Real>()) {
37
38 Size m = A.rows();
39 Size n = A.columns();
40
41 SVD svd(A);
42
43 Real tol0 = tol;
44 if (tol0 == Null<Real>()) {
45 tol0 = std::max(m, n) * QL_EPSILON * std::abs(svd.singularValues()[0]);
46 }
47
48 Matrix sp(n, n, 0.0);
49 for (Size i = 0; i < n; ++i) {
50 if (std::abs(svd.singularValues()[i]) > tol0) {
51 sp(i, i) = 1.0 / svd.singularValues()[i];
52 }
53 }
54
55 Matrix res = svd.V() * sp * transpose(svd.U());
56 return res;
57};
58
59} // namespace QuantLib
60
61#endif // include guard
Matrix used in linear algebra.
Definition: matrix.hpp:41
Size rows() const
Definition: matrix.hpp:504
Size columns() const
Definition: matrix.hpp:508
template class providing a null value for a given type.
Definition: null.hpp:76
Singular value decomposition.
Definition: svd.hpp:54
const Matrix & V() const
Definition: svd.cpp:489
const Array & singularValues() const
Definition: svd.cpp:493
const Matrix & U() const
Definition: svd.cpp:485
#define QL_EPSILON
Definition: qldefines.hpp:178
QL_REAL Real
real number
Definition: types.hpp:50
std::size_t Size
size of a container
Definition: types.hpp:58
Definition: any.hpp:35
Matrix moorePenroseInverse(const Matrix &A, const Real tol=Null< Real >())
Matrix transpose(const Matrix &m)
Definition: matrix.hpp:700