QuantLib: a free/open-source library for quantitative finance
fully annotated source code - version 1.34
Loading...
Searching...
No Matches
expm.cpp
Go to the documentation of this file.
1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2013 Klaus Spanderen
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
20/*! \file expm.cpp
21 \brief matrix exponential
22*/
23
24
27#include <algorithm>
28#include <numeric>
29#include <utility>
30
31namespace QuantLib {
32
33 namespace {
34 class MatrixVectorProductFct {
35 public:
36 explicit MatrixVectorProductFct(Matrix m) : m_(std::move(m)) {}
37
38 // implements x = M*y
39 std::vector<Real> operator()(Real t, const std::vector<Real>& y) {
40
41 std::vector<Real> result(m_.rows());
42 for (Size i=0; i < result.size(); i++) {
43 result[i] = std::inner_product(y.begin(), y.end(),
44 m_.row_begin(i), Real(0.0));
45 }
46 return result;
47 }
48 private:
49 const Matrix m_;
50 };
51 }
52
53 Matrix Expm(const Matrix& M, Real t, Real tol) {
54 const Size n = M.rows();
55 QL_REQUIRE(n == M.columns(), "Expm expects a square matrix");
56
58 AdaptiveRungeKutta<>::OdeFct odeFct = MatrixVectorProductFct(M);
59
60 Matrix result(n, n);
61 for (Size i=0; i < n; ++i) {
62 std::vector<Real> x0(n, 0.0);
63 x0[i] = 1.0;
64
65 const std::vector<Real> r = rk(odeFct, x0, 0.0, t);
66 std::copy(r.begin(), r.end(), result.column_begin(i));
67 }
68 return result;
69 }
70}
Runge-Kutta ODE integration.
ext::function< std::vector< T >(const Real, const std::vector< T > &)> OdeFct
Matrix used in linear algebra.
Definition: matrix.hpp:41
Size rows() const
Definition: matrix.hpp:504
Size columns() const
Definition: matrix.hpp:508
const_column_iterator column_begin(Size i) const
Definition: matrix.hpp:415
const DefaultType & t
#define QL_REQUIRE(condition, message)
throw an error if the given pre-condition is not verified
Definition: errors.hpp:117
const Matrix m_
Definition: expm.cpp:49
matrix exponential
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 Expm(const Matrix &M, Real t, Real tol)
matrix exponential based on the ordinary differential equations method
Definition: expm.cpp:53
STL namespace.
ext::shared_ptr< YieldTermStructure > r