Hamiltonian Monte Carlo

randomnumbers.cpp
Go to the documentation of this file.
1 //
2 // Created by Lars Gebraad on 7/10/17.
3 //
4 #include <cstdlib>
5 #include "randomnumbers.hpp"
6 #include "linearalgebra.hpp"
7 #include <cmath>
8 #include <utility>
9 #include <vector>
10 
11 // Random number generators
12 /* Uniformly distributed, double-valued random numbers. ---------------------------*/
13 double randf(double min, double max) {
14  return (max - min) * (double) rand() / RAND_MAX + min;
15 }
16 
17 double randn(double mean, double stdv) {
18  double x;
19 
20  double z1 = (double) rand() / RAND_MAX;
21  double z2 = (double) rand() / RAND_MAX;
22 
23  x = sqrt(-2.0 * log(z1)) * cos(2.0 * PI * z2);
24  x = stdv * x + mean;
25 
26  return x;
27 }
28 
29 
30 std::vector<double> randn(std::vector<double> means, std::vector<double> stdv) {
31  std::vector<double> samples;
32  samples = means + randn(std::move(stdv));
33  return samples;
34 }
35 
36 std::vector<double> randn(std::vector<double> stdv) {
37  // Zero mean
38  std::vector<double> samples;
39  samples.reserve(stdv.size());
40  for (double i : stdv) {
41  samples.push_back(randn(0, i));
42  }
43  return samples;
44 }
45 
46 std::vector<double>
47 randn_Cholesky(std::vector<double> mean, std::vector<std::vector<double>> CholeskyLower_CovarianceMatrix) {
48  return mean + randn_Cholesky(std::move(CholeskyLower_CovarianceMatrix));
49 }
50 
51 std::vector<double> randn_Cholesky(std::vector<std::vector<double>> CholeskyLower_CovarianceMatrix) {
52  // Assumes zero mean
53  std::vector<double> uncorrelated;
54  uncorrelated.reserve(CholeskyLower_CovarianceMatrix.size());
55  for (int i = 0; i < CholeskyLower_CovarianceMatrix.size(); ++i) {
56  uncorrelated.push_back(randn(0, 1));
57  }
58  return std::move(CholeskyLower_CovarianceMatrix) * uncorrelated;
59 
60 }
61 
62 std::vector<double> randn(std::vector<std::vector<double>> DiagonalCovarianceMatrix) {
63  std::vector<double> samples;
64  samples.reserve(DiagonalCovarianceMatrix.size());
65  for (int i = 0; i < DiagonalCovarianceMatrix.size(); i++) {
66  samples.push_back(randn(0, sqrt(DiagonalCovarianceMatrix[i][i])));
67  }
68  return samples;
69 }
const double PI
double randf(double min, double max)
Draw uniformly distributed samples between two numbers.
Set of functions to draw from (multivariate, correlated) normal distributions.
std::vector< double > randn_Cholesky(std::vector< double > mean, std::vector< std::vector< double >> CholeskyLower_CovarianceMatrix)
Drawing non-zero mean samples from an dimensional correlated Gaussian. Invokes randn_Cholesky(std::v...
double randn(double mean, double stdv)
Draws from Gaussian (mean, standard deviation) using Box-Müller transform.
Linear algebra functions operating on standard library containers.