diff options
author | Marc Sunet <msunet@shellblade.net> | 2022-05-11 09:56:33 -0700 |
---|---|---|
committer | Marc Sunet <msunet@shellblade.net> | 2022-05-11 09:56:33 -0700 |
commit | 685950d3f2ac8e893a23443f9e087294cce2c6fa (patch) | |
tree | c348f368d9e6245952321332c80658853348396e | |
parent | d52ef50957064da5dbfb76839e009c48ff2050c6 (diff) |
Add random variable.
-rw-r--r-- | random/CMakeLists.txt | 3 | ||||
-rw-r--r-- | random/include/random/normal.h | 9 | ||||
-rw-r--r-- | random/include/random/random.h | 2 | ||||
-rw-r--r-- | random/src/normal.c | 17 |
4 files changed, 30 insertions, 1 deletions
diff --git a/random/CMakeLists.txt b/random/CMakeLists.txt index ec80b1d..188d16b 100644 --- a/random/CMakeLists.txt +++ b/random/CMakeLists.txt | |||
@@ -3,7 +3,8 @@ cmake_minimum_required(VERSION 3.0) | |||
3 | project(random) | 3 | project(random) |
4 | 4 | ||
5 | add_library(random | 5 | add_library(random |
6 | src/mt19937-64.c) | 6 | src/mt19937-64.c |
7 | src/normal.c) | ||
7 | 8 | ||
8 | target_include_directories(random PUBLIC include) | 9 | target_include_directories(random PUBLIC include) |
9 | 10 | ||
diff --git a/random/include/random/normal.h b/random/include/random/normal.h new file mode 100644 index 0000000..bee32a9 --- /dev/null +++ b/random/include/random/normal.h | |||
@@ -0,0 +1,9 @@ | |||
1 | #pragma once | ||
2 | |||
3 | /// Generate two samples from the standard normal distribution. | ||
4 | /// | ||
5 | /// |u| and |v| must be uniformly distributed in (0,1). | ||
6 | void normal2(double u, double v, double* z0, double* z1); | ||
7 | |||
8 | /// Map a sample from a standard normal distribution to an arbitrary normal. | ||
9 | double normal_transform(double z, double mu, double sigma); | ||
diff --git a/random/include/random/random.h b/random/include/random/random.h index 5499f62..1f4a48d 100644 --- a/random/include/random/random.h +++ b/random/include/random/random.h | |||
@@ -1,3 +1,5 @@ | |||
1 | #pragma once | 1 | #pragma once |
2 | 2 | ||
3 | #include <random/mt19937-64.h> | 3 | #include <random/mt19937-64.h> |
4 | #include <random/normal.h> | ||
5 | |||
diff --git a/random/src/normal.c b/random/src/normal.c new file mode 100644 index 0000000..d4bcac1 --- /dev/null +++ b/random/src/normal.c | |||
@@ -0,0 +1,17 @@ | |||
1 | #include <random/normal.h> | ||
2 | |||
3 | #include <math.h> | ||
4 | |||
5 | // Generate two samples in the standard normal distribution using the | ||
6 | // Box-Muller transform. | ||
7 | // https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform | ||
8 | void normal2(double u, double v, double* z0, double* z1) { | ||
9 | const double r = sqrt(-2 * log(u)); | ||
10 | const double x = 2 * M_PI * v; | ||
11 | *z0 = r * cos(x); | ||
12 | *z1 = r * sin(x); | ||
13 | } | ||
14 | |||
15 | double normal_transform(double z, double mu, double sigma) { | ||
16 | return z*sigma + mu; | ||
17 | } | ||