1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2014 Klaus Spanderen
5
6 This file is part of QuantLib, a free-software/open-source library
7 for financial quantitative analysts and developers - http://quantlib.org/
8
9 QuantLib is free software: you can redistribute it and/or modify it
10 under the terms of the QuantLib license. You should have received a
11 copy of the license along with this program; if not, please email
12 <quantlib-dev@lists.sf.net>. The license is also available online at
13 <http://quantlib.org/license.shtml>.
14
15 This program is distributed in the hope that it will be useful, but WITHOUT
16 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 FOR A PARTICULAR PURPOSE. See the license for more details.
18*/
19
20/*! \file filonintegral.cpp
21 \brief Filon's formulae for sine and cosine Integrals
22*/
23
24#include <ql/errors.hpp>
25#include <ql/utilities/null.hpp>
26#include <ql/math/array.hpp>
27#include <ql/math/functional.hpp>
28#include <ql/math/integrals/filonintegral.hpp>
29
30#include <cmath>
31
32namespace QuantLib {
33 FilonIntegral::FilonIntegral(Type type, Real t, Size intervals)
34 : Integrator(Null<Real>(), intervals+1),
35 type_(type),
36 t_(t),
37 intervals_(intervals),
38 n_ (intervals/2){
39 QL_REQUIRE( !(intervals_ & 1), "number of intervals must be even");
40 }
41
42 Real FilonIntegral::integrate(const ext::function<Real (Real)>& f,
43 Real a, Real b) const {
44 const Real h = (b-a)/(2*n_);
45 Array x(2*n_+1, a, h);
46
47 const Real theta = t_*h;
48 const Real theta2 = theta*theta;
49 const Real theta3 = theta2*theta;
50
51 const Real alpha = 1/theta + std::sin(x: 2*theta)/(2*theta2)
52 - 2*squared(x: std::sin(x: theta))/theta3;
53 const Real beta = 2*( (1+squared(x: std::cos(x: theta)))/theta2
54 - std::sin(x: 2*theta)/theta3);
55 const Real gamma = 4*(std::sin(x: theta)/theta3 - std::cos(x: theta)/theta2);
56
57 Array v(x.size());
58 std::transform(first: x.begin(), last: x.end(), result: v.begin(), unary_op: f);
59
60 ext::function<Real(Real)> f1, f2;
61 switch(type_) {
62 case Cosine:
63 f1 = [](Real x) -> Real { return std::sin(x: x); };
64 f2 = [](Real x) -> Real { return std::cos(x: x); };
65 break;
66 case Sine:
67 f1 = [](Real x) -> Real { return std::cos(x: x); };
68 f2 = [](Real x) -> Real { return std::sin(x: x); };
69 break;
70 default:
71 QL_FAIL("unknown integration type");
72 }
73
74 Real c_2n_1 = 0.0;
75 Real c_2n = v[0]*f2(t_*a)
76 - 0.5*(v[2*n_]*f2(t_*b) + v[0]*f2(t_*a));
77
78 for (Size i=1; i <= n_; ++i) {
79 c_2n += v[2*i] *f2(t_*x[2*i]);
80 c_2n_1 += v[2*i-1]*f2(t_*x[2*i-1]);
81 }
82
83 return h*(alpha*(v[2*n_]*f1(t_*x[2*n_]) - v[0]*f1(t_*x[0]))
84 *((type_ == Cosine) ? 1.0 : -1.0)
85 + beta*c_2n + gamma*c_2n_1);
86 }
87}
88

source code of quantlib/ql/math/integrals/filonintegral.cpp