/src/quantlib/ql/math/distributions/studenttdistribution.cpp
Line | Count | Source |
1 | | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
2 | | |
3 | | /* |
4 | | Copyright (C) 2008 Roland Lichters |
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 | | <https://www.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 | | #include <ql/math/distributions/studenttdistribution.hpp> |
21 | | #include <ql/math/distributions/gammadistribution.hpp> |
22 | | #include <ql/math/beta.hpp> |
23 | | |
24 | | namespace QuantLib { |
25 | | |
26 | 0 | Real StudentDistribution::operator()(Real x) const { |
27 | 0 | static GammaFunction G; |
28 | 0 | Real g1 = std::exp (G.logValue(0.5 * (n_ + 1))); |
29 | 0 | Real g2 = std::exp (G.logValue(0.5 * n_)); |
30 | |
|
31 | 0 | Real power = std::pow (1. + x*x / n_, 0.5 * (n_ + 1)); |
32 | |
|
33 | 0 | return g1 / (g2 * power * std::sqrt (M_PI * n_)); |
34 | 0 | } |
35 | | |
36 | 0 | Real CumulativeStudentDistribution::operator()(Real x) const { |
37 | 0 | Real xx = 1.0 * n_ / (x*x + n_); |
38 | 0 | Real sig = (x > 0 ? 1.0 : - 1.0); |
39 | |
|
40 | 0 | return 0.5 + 0.5 * sig * ( incompleteBetaFunction (0.5 * n_, 0.5, 1.0) |
41 | 0 | -incompleteBetaFunction (0.5 * n_, 0.5, xx)); |
42 | 0 | } |
43 | | |
44 | 0 | Real InverseCumulativeStudent::operator()(Real y) const { |
45 | 0 | QL_REQUIRE (y >= 0 && y <= 1, "argument out of range [0, 1]"); |
46 | | |
47 | 0 | Real x = 0; |
48 | 0 | Size count = 0; |
49 | | |
50 | | // do a few newton steps to find x |
51 | 0 | do { |
52 | 0 | x -= (f_(x) - y) / d_(x); |
53 | 0 | count++; |
54 | 0 | } |
55 | 0 | while (std::fabs(f_(x) - y) > accuracy_ && count < maxIterations_); |
56 | |
|
57 | 0 | QL_REQUIRE (count < maxIterations_, |
58 | 0 | "maximum number of iterations " << maxIterations_ |
59 | 0 | << " reached in InverseCumulativeStudent, " |
60 | 0 | << "y=" << y << ", x=" << x); |
61 | | |
62 | 0 | return x; |
63 | 0 | } |
64 | | |
65 | | } |
66 | | |