QuantLib: a free/open-source library for quantitative finance
fully annotated source code - version 1.34
Loading...
Searching...
No Matches
choleskydecomposition.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) 2003, 2004 Ferdinando Ametrano
5 Copyright (C) 2016 Peter Caspers
6
7 This file is part of QuantLib, a free-software/open-source library
8 for financial quantitative analysts and developers - http://quantlib.org/
9
10 QuantLib is free software: you can redistribute it and/or modify it
11 under the terms of the QuantLib license. You should have received a
12 copy of the license along with this program; if not, please email
13 <quantlib-dev@lists.sf.net>. The license is also available online at
14 <http://quantlib.org/license.shtml>.
15
16 This program is distributed in the hope that it will be useful, but WITHOUT
17 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 FOR A PARTICULAR PURPOSE. See the license for more details.
19*/
20
23
24namespace QuantLib {
25
26 Matrix CholeskyDecomposition(const Matrix& S, bool flexible) {
27 Size i, j, size = S.rows();
28
29 QL_REQUIRE(size == S.columns(),
30 "input matrix is not a square matrix");
31 #if defined(QL_EXTRA_SAFETY_CHECKS)
32 for (i=0; i<S.rows(); i++)
33 for (j=0; j<i; j++)
34 QL_REQUIRE(S[i][j] == S[j][i],
35 "input matrix is not symmetric");
36 #endif
37
38 Matrix result(size, size, 0.0);
39 Real sum;
40 for (i=0; i<size; i++) {
41 for (j=i; j<size; j++) {
42 sum = S[i][j];
43 for (Integer k=0; k<=Integer(i)-1; k++) {
44 sum -= result[i][k]*result[j][k];
45 }
46 if (i == j) {
47 QL_REQUIRE(flexible || sum > 0.0,
48 "input matrix is not positive definite");
49 // To handle positive semi-definite matrices take the
50 // square root of sum if positive, else zero.
51 result[i][i] = std::sqrt(std::max<Real>(sum, 0.0));
52 } else {
53 // With positive semi-definite matrices is possible
54 // to have result[i][i]==0.0
55 // In this case sum happens to be zero as well
56 result[j][i] = close_enough(result[i][i], 0.0)
57 ? 0.0
58 : Real(sum / result[i][i]);
59 }
60 }
61 }
62 return result;
63 }
64}
Cholesky decomposition.
Matrix used in linear algebra.
Definition: matrix.hpp:41
floating-point comparisons
#define QL_REQUIRE(condition, message)
throw an error if the given pre-condition is not verified
Definition: errors.hpp:117
QL_REAL Real
real number
Definition: types.hpp:50
QL_INTEGER Integer
integer number
Definition: types.hpp:35
std::size_t Size
size of a container
Definition: types.hpp:58
Definition: any.hpp:35
Matrix CholeskyDecomposition(const Matrix &S, bool flexible)
bool close_enough(const Quantity &m1, const Quantity &m2, Size n)
Definition: quantity.cpp:182