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 <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 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
30namespace 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 : TrapezoidIntegral<Default>(accuracy, maxIterations) {}
41 protected:
42 Real integrate(const ext::function<Real(Real)>& f, Real a, Real b) const override {
43
44 // start from the coarsest trapezoid...
45 Size N = 1;
46 Real I = (f(a)+f(b))*(b-a)/2.0, newI;
47 Real adjI = I, newAdjI;
48 // ...and refine it
49 Size i = 1;
50 do {
51 newI = Default::integrate(f,a,b,I,N);
52 N *= 2;
53 newAdjI = (4.0*newI-I)/3.0;
54 // good enough? Also, don't run away immediately
55 if (std::fabs(x: adjI-newAdjI) <= absoluteAccuracy() && i > 5)
56 // ok, exit
57 return newAdjI;
58 // oh well. Another step.
59 I = newI;
60 adjI = newAdjI;
61 i++;
62 } while (i < maxEvaluations());
63 QL_FAIL("max number of iterations reached");
64 }
65 };
66
67}
68
69#endif
70

source code of quantlib/ql/math/integrals/simpsonintegral.hpp