/src/quantlib/ql/math/integrals/simpsonintegral.hpp
Line | Count | Source (jump to first uncovered line) |
1 | | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
2 | | |
3 | | /* |
4 | | Copyright (C) 2003 Roman Gitlin |
5 | | Copyright (C) 2003 StatPro Italia srl |
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 | | <https://www.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 simpsonintegral.hpp |
22 | | \brief integral of a one-dimensional function using Simpson formula |
23 | | */ |
24 | | |
25 | | #ifndef quantlib_simpson_integral_hpp |
26 | | #define quantlib_simpson_integral_hpp |
27 | | |
28 | | #include <ql/math/integrals/trapezoidintegral.hpp> |
29 | | |
30 | | namespace QuantLib { |
31 | | |
32 | | //! Integral of a one-dimensional function |
33 | | /*! \test the correctness of the result is tested by checking it |
34 | | against known good values. |
35 | | */ |
36 | | class SimpsonIntegral : public TrapezoidIntegral<Default> { |
37 | | public: |
38 | | SimpsonIntegral(Real accuracy, |
39 | | Size maxIterations) |
40 | 0 | : TrapezoidIntegral<Default>(accuracy, maxIterations) {} |
41 | | protected: |
42 | 0 | Real integrate(const std::function<Real(Real)>& f, Real a, Real b) const override { |
43 | | |
44 | | // start from the coarsest trapezoid... |
45 | 0 | Size N = 1; |
46 | 0 | Real I = (f(a)+f(b))*(b-a)/2.0, newI; |
47 | 0 | increaseNumberOfEvaluations(2); |
48 | |
|
49 | 0 | Real adjI = I, newAdjI; |
50 | | // ...and refine it |
51 | 0 | Size i = 1; |
52 | 0 | do { |
53 | 0 | newI = Default::integrate(f,a,b,I,N); |
54 | 0 | increaseNumberOfEvaluations(N); |
55 | 0 | N *= 2; |
56 | 0 | newAdjI = (4.0*newI-I)/3.0; |
57 | | // good enough? Also, don't run away immediately |
58 | 0 | if (std::fabs(adjI-newAdjI) <= absoluteAccuracy() && i > 5) |
59 | | // ok, exit |
60 | 0 | return newAdjI; |
61 | | // oh well. Another step. |
62 | 0 | I = newI; |
63 | 0 | adjI = newAdjI; |
64 | 0 | i++; |
65 | 0 | } while (i < maxEvaluations()); |
66 | 0 | QL_FAIL("max number of iterations reached"); |
67 | 0 | } |
68 | | }; |
69 | | |
70 | | } |
71 | | |
72 | | #endif |