Skip to content

Commit 020d3d7

Browse files
committed
std::normal_distribution
1 parent 87ba14b commit 020d3d7

File tree

2 files changed

+12
-30
lines changed

2 files changed

+12
-30
lines changed

Diff for: .gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ compile_commands.json
66

77
#ide
88
.idea
9-
9+
test.cpp
10+
a.out

Diff for: examples/monte-carlo-calculator/main.cpp

+10-29
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,29 @@
11
#include <aws/lambda-runtime/runtime.h>
22
#include <iomanip>
33
#include <sstream>
4-
#include <algorithm> // Needed for the "max" function
4+
#include <algorithm>
55
#include <cmath>
66
#include <iostream>
7+
#include <random>
78
#include <aws/core/utils/json/JsonSerializer.h>
89
#include <aws/core/utils/memory/stl/SimpleStringStream.h>
910

1011
using namespace aws::lambda_runtime;
1112
using namespace Aws::Utils::Json;
1213

13-
14-
15-
// A simple implementation of the Box-Muller algorithm, used to generate
16-
// gaussian random numbers - necessary for the Monte Carlo method below
17-
// Note that C++11 actually provides std::normal_distribution<> in
18-
// the <random> library, which can be used instead of this function
19-
double gaussian_box_muller() {
20-
double x = 0.0;
21-
double y = 0.0;
22-
double euclid_sq = 0.0;
23-
24-
// Continue generating two uniform random variables
25-
// until the square of their "euclidean distance"
26-
// is less than unity
27-
do {
28-
x = 2.0 * rand() / static_cast<double>(RAND_MAX)-1;
29-
y = 2.0 * rand() / static_cast<double>(RAND_MAX)-1;
30-
euclid_sq = x*x + y*y;
31-
} while (euclid_sq >= 1.0);
32-
33-
return x*sqrt(-2*log(euclid_sq)/euclid_sq);
34-
}
35-
3614
// Pricing a European vanilla call option with a Monte Carlo method
3715
double monte_carlo_call_price(const int& num_sims, const double& S, const double& K, const double& r, const double& v, const double& T) {
38-
double S_adjust = S * exp(T*(r-0.5*v*v));
39-
double S_cur = 0.0;
16+
double s_adjust = S * exp(T*(r-0.5*v*v));
17+
double s_cur = 0.0;
4018
double payoff_sum = 0.0;
4119

20+
std::random_device rd {};
21+
std::mt19937 prng {rd()};
22+
std::normal_distribution<> d {0, 1};
23+
4224
for (int i=0; i<num_sims; i++) {
43-
double gauss_bm = gaussian_box_muller();
44-
S_cur = S_adjust * exp(sqrt(v*v*T)*gauss_bm);
45-
payoff_sum += std::max(S_cur - K, 0.0);
25+
s_cur = s_adjust * exp(sqrt(v*v*T)*d(prng));
26+
payoff_sum += std::max(s_cur - K, 0.0);
4627
}
4728

4829
return (payoff_sum / static_cast<double>(num_sims)) * exp(-r*T);

0 commit comments

Comments
 (0)