1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2009 Ralph Schreyer
5 Copyright (C) 2009 Klaus Spanderen
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
21/*! \file bicgstab.cpp
22 \brief bi-conjugated gradient stableized algorithm
23*/
24
25
26#include <ql/math/matrixutilities/bicgstab.hpp>
27#include <utility>
28
29namespace QuantLib {
30
31 BiCGstab::BiCGstab(BiCGstab::MatrixMult A,
32 Size maxIter,
33 Real relTol,
34 BiCGstab::MatrixMult preConditioner)
35 : A_(std::move(A)), M_(std::move(preConditioner)), maxIter_(maxIter), relTol_(relTol) {}
36
37 BiCGStabResult BiCGstab::solve(const Array& b, const Array& x0) const {
38 Real bnorm2 = Norm2(v: b);
39 if (bnorm2 == 0.0) {
40 BiCGStabResult result = { .iterations: 0, .error: 0.0, .x: b};
41 return result;
42 }
43
44 Array x = ((!x0.empty()) ? x0 : Array(b.size(), 0.0));
45 Array r = b - A_(x);
46
47 Array rTld = r;
48 Array p, pTld, v, s, sTld, t;
49 Real omega = 1.0;
50 Real rho, rhoTld=1.0;
51 Real alpha = 0.0, beta;
52 Real error = Norm2(v: r)/bnorm2;
53
54 Size i;
55 for (i=0; i < maxIter_ && error >= relTol_; ++i) {
56 rho = DotProduct(v1: rTld, v2: r);
57 if (rho == 0.0 || omega == 0.0)
58 break;
59
60 if (i != 0U) {
61 beta = (rho / rhoTld) * (alpha / omega);
62 p = r + beta * (p - omega * v);
63 } else {
64 p = r;
65 }
66
67 pTld = (!M_ ? p : M_(p));
68 v = A_(pTld);
69
70 alpha = rho/DotProduct(v1: rTld, v2: v);
71 s = r-alpha*v;
72 if (Norm2(v: s) < relTol_*bnorm2) {
73 x += alpha*pTld;
74 error = Norm2(v: s)/bnorm2;
75 break;
76 }
77
78 sTld = (!M_ ? s : M_(s));
79 t = A_(sTld);
80 omega = DotProduct(v1: t,v2: s)/DotProduct(v1: t,v2: t);
81 x += alpha*pTld + omega*sTld;
82 r = s - omega*t;
83 error = Norm2(v: r)/bnorm2;
84 rhoTld = rho;
85 }
86
87 QL_REQUIRE(i < maxIter_, "max number of iterations exceeded");
88 QL_REQUIRE(error < relTol_, "could not converge");
89
90 BiCGStabResult result = { .iterations: i, .error: error, .x: x};
91 return result;
92 }
93
94}
95

source code of quantlib/ql/math/matrixutilities/bicgstab.cpp