| 1 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
| 2 | |
| 3 | /* |
| 4 | Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl |
| 5 | Copyright (C) 2015 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 | |
| 21 | /*! \file segmentintegral.hpp |
| 22 | \brief Integral of a one-dimensional function using segment algorithm |
| 23 | */ |
| 24 | |
| 25 | #ifndef quantlib_segment_integral_h |
| 26 | #define quantlib_segment_integral_h |
| 27 | |
| 28 | #include <ql/math/integrals/integral.hpp> |
| 29 | #include <ql/math/comparison.hpp> |
| 30 | #include <ql/errors.hpp> |
| 31 | |
| 32 | namespace QuantLib { |
| 33 | |
| 34 | //! Integral of a one-dimensional function |
| 35 | /*! Given a number \f$ N \f$ of intervals, the integral of |
| 36 | a function \f$ f \f$ between \f$ a \f$ and \f$ b \f$ is |
| 37 | calculated by means of the trapezoid formula |
| 38 | \f[ |
| 39 | \int_{a}^{b} f \mathrm{d}x = |
| 40 | \frac{1}{2} f(x_{0}) + f(x_{1}) + f(x_{2}) + \dots |
| 41 | + f(x_{N-1}) + \frac{1}{2} f(x_{N}) |
| 42 | \f] |
| 43 | where \f$ x_0 = a \f$, \f$ x_N = b \f$, and |
| 44 | \f$ x_i = a+i \Delta x \f$ with |
| 45 | \f$ \Delta x = (b-a)/N \f$. |
| 46 | |
| 47 | \test the correctness of the result is tested by checking it |
| 48 | against known good values. |
| 49 | */ |
| 50 | class SegmentIntegral : public Integrator { |
| 51 | public: |
| 52 | explicit SegmentIntegral(Size intervals); |
| 53 | protected: |
| 54 | Real integrate(const ext::function<Real(Real)>& f, Real a, Real b) const override; |
| 55 | |
| 56 | private: |
| 57 | Size intervals_; |
| 58 | }; |
| 59 | |
| 60 | |
| 61 | // inline and template definitions |
| 62 | |
| 63 | inline Real |
| 64 | SegmentIntegral::integrate(const ext::function<Real (Real)>& f, |
| 65 | Real a, |
| 66 | Real b) const { |
| 67 | if(close_enough(x: a,y: b)) |
| 68 | return 0.0; |
| 69 | Real dx = (b-a)/intervals_; |
| 70 | Real sum = 0.5*(f(a)+f(b)); |
| 71 | Real end = b - 0.5*dx; |
| 72 | for (Real x = a+dx; x < end; x += dx) |
| 73 | sum += f(x); |
| 74 | return sum*dx; |
| 75 | } |
| 76 | |
| 77 | } |
| 78 | |
| 79 | #endif |
| 80 | |