vnl_sample.cxx
Go to the documentation of this file.
1 // This is core/vnl/vnl_sample.cxx
2 
3 #include <cmath>
4 #include <ctime>
5 #include "vnl_sample.h"
6 #include <vnl/vnl_math.h>
7 #include "vnl_drand48.h"
8 
10 {
11  vnl_srand48( std::time(0) );
12 }
13 
14 void vnl_sample_reseed(int seed)
15 {
16  vnl_srand48( seed );
17 }
18 
19 double vnl_sample_uniform(double a, double b)
20 {
21  double u = vnl_drand48(); // uniform on [0, 1)
22  return (1.0 - u)*a + u*b;
23 }
24 
26 {
27  return vnl_sample_uniform(0.0, 1.0); // uniform on [0, 1)
28 }
29 
30 void vnl_sample_normal_2(double *x, double *y)
31 {
32  double u = vnl_sample_uniform(1, 0); // not (0,1): should not return 0
33  double theta = vnl_sample_uniform(0, vnl_math::twopi);
34 
35  double r = std::sqrt(-2*std::log(u));
36 
37  if (x) *x = r * std::cos(theta);
38  if (y) *y = r * std::sin(theta);
39 }
40 
41 double vnl_sample_normal(double mean, double sigma)
42 {
43  double x;
44  vnl_sample_normal_2(&x, nullptr);
45  return mean + sigma * x;
46 }
47 
48 // Implementation of Bernoulli sampling by Peter Vanroose
49 int vnl_sample_bernoulli(double q)
50 {
51  // quick return if possible:
52  if (q==0.0) return 0;
53  if (q==1.0) return 1;
54  if (q<0.0 || q>1.0) return -1;
55  // q should be the probability of returning 0:
56  return (vnl_sample_uniform(0.0, 1.0/q) >= 1.0) ? 1 : 0;
57 }
58 
59 // Implementation of binomial sampling by Peter Vanroose
60 int vnl_sample_binomial(int n, double q)
61 {
62  // Returns a random "k" value, between 0 and n, viz. the sum of n random
63  // and independent drawings from a Bernoulli distribution with parameter q.
64 
65  if (n <= 0 || q<0.0 || q>1.0) return -1; // That is: when the input makes no sense, return nonsense "-1".
66  if (q==0.0) return 0;
67  if (q==1.0) return n;
68  int k = 0;
69  for (int i=n-1; i>=0; --i) {
70  k += vnl_sample_bernoulli(q);
71  }
72  return k;
73 }
int vnl_sample_binomial(int n, double q)
Return random k, where P(X = k) = [kth term in binomial expansion of (q + (1-q))^n].
Definition: vnl_sample.cxx:60
double vnl_sample_uniform(double a, double b)
return a random number uniformly drawn on [a, b).
Definition: vnl_sample.cxx:19
Namespace with standard math functions.
void vnl_srand48(long seed)
void vnl_sample_normal_2(double *x, double *y)
two independent samples from a standard normal distribution.
Definition: vnl_sample.cxx:30
int vnl_sample_bernoulli(double q)
Bernoulli distribution ("coin toss").
Definition: vnl_sample.cxx:49
void vnl_sample_reseed()
re-seed the random number generator.
Definition: vnl_sample.cxx:9
easy ways to sample from various probability distributions
double vnl_drand48()
T mean() const
Return mean of all matrix elements.
double vnl_sample_uniform01()
return a random number uniformly drawn on [0, 1.0).
Definition: vnl_sample.cxx:25
double vnl_sample_normal(double mean, double sigma)
Normal distribution with given mean and standard deviation.
Definition: vnl_sample.cxx:41