-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNormals.cpp
135 lines (102 loc) · 3.12 KB
/
Normals.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//
//
// Normals.cpp
//
//
/*
code to implement the basic distribution functions necessary in mathematical finance
via rational approximations
*/
#include <cmath>
#include "Normals.h"
// the basic math functions should be in namespace std but aren't in VCPP6
#if !defined(_MSC_VER)
using namespace std;
#endif
const double OneOverRootTwoPi = 0.398942280401433;
// probability density for a standard Gaussian distribution
double NormalDensity(double x)
{
return OneOverRootTwoPi*exp(-x*x/2);
}
// the InverseCumulativeNormal function via the Beasley-Springer/Moro approximation
double InverseCumulativeNormal(double u)
{
static double a[4]={ 2.50662823884,
-18.61500062529,
41.39119773534,
-25.44106049637};
static double b[4]={-8.47351093090,
23.08336743743,
-21.06224101826,
3.13082909833};
static double c[9]={0.3374754822726147,
0.9761690190917186,
0.1607979714918209,
0.0276438810333863,
0.0038405729373609,
0.0003951896511919,
0.0000321767881768,
0.0000002888167364,
0.0000003960315187};
double x=u-0.5;
double r;
if (fabs(x)<0.42) // Beasley-Springer
{
double y=x*x;
r=x*(((a[3]*y+a[2])*y+a[1])*y+a[0])/
((((b[3]*y+b[2])*y+b[1])*y+b[0])*y+1.0);
}
else // Moro
{
r=u;
if (x>0.0)
r=1.0-u;
r=log(-log(r));
r=c[0]+r*(c[1]+r*(c[2]+r*(c[3]+r*(c[4]+r*(c[5]+r*(c[6]+
r*(c[7]+r*c[8])))))));
if (x<0.0)
r=-r;
}
return r;
}
// standard normal cumulative distribution function
double CumulativeNormal(double x)
{
static double a[5] = { 0.319381530,
-0.356563782,
1.781477937,
-1.821255978,
1.330274429};
double result;
if (x<-7.0)
result = NormalDensity(x)/sqrt(1.+x*x);
else
{
if (x>7.0)
result = 1.0 - CumulativeNormal(-x);
else
{
double tmp = 1.0/(1.0+0.2316419*fabs(x));
result=1-NormalDensity(x)*
(tmp*(a[0]+tmp*(a[1]+tmp*(a[2]+tmp*(a[3]+tmp*a[4])))));
if (x<=0.0)
result=1.0-result;
}
}
return result;
}
/*
*
* Copyright (c) 2002
* Mark Joshi
*
* Permission to use, copy, modify, distribute and sell this
* software for any purpose is hereby
* granted without fee, provided that the above copyright notice
* appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation.
* Mark Joshi makes no representations about the
* suitability of this software for any purpose. It is provided
* "as is" without express or implied warranty.
*/