YARP
Yet Another Robot Platform
RandnScalar.cpp
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3  * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
8 #include <yarp/math/RandScalar.h>
9 #include <yarp/sig/Vector.h>
10 #include <ctime>
11 #include <cstdio>
12 #include <cmath>
13 
14 using namespace yarp::sig;
15 using namespace yarp::math;
16 
17 inline RandScalar *implementation(void *t)
18 {
19  return static_cast<RandScalar*>(t);
20 }
21 
22 RandnScalar::RandnScalar()
23 {
24  impl = new RandScalar;
25  init();
26 }
27 
28 RandnScalar::RandnScalar(int seed)
29 {
30  impl = new RandScalar;
31  init(seed);
32 }
33 
34 RandnScalar::~RandnScalar()
35 {
36  delete (implementation(impl));
37 }
38 
39 // initialize with a call to "time"
40 void RandnScalar::init()
41 {
42  // initialize with time
43  int t=(int)time(nullptr);
44  RandnScalar::init(t);
45 }
46 
47 void RandnScalar::init(int s)
48 {
49  //force re-execution of BoxMuller
50  executeBoxMuller = true;
51  seed=s;
52  implementation(impl)->init(s);
53 }
54 
55 double RandnScalar::get(double u, double sigma)
56 {
57  // BoxMuller generates two numbers every iteration
58  // we return y[0] the first time, and y[1] the second time
59  if (executeBoxMuller)
60  {
61  boxMuller();
62  return y[0] * sigma + u;
63  }
64  else
65  {
66  executeBoxMuller = true;
67  return y[1] * sigma + u;
68  }
69 }
70 
71 void RandnScalar::boxMuller()
72 {
73  double x1 = 0.0;
74  double x2 = 0.0;
75  double w = 2.0;
76 
77  while (w >= 1.0)
78  {
79  x1 = 2.0 * implementation(impl)->get() - 1.0;
80  x2 = 2.0 * implementation(impl)->get() - 1.0;
81  w = x1 * x1 + x2 * x2;
82  }
83 
84  w = sqrt( (-2.0 * log( w ) ) / w );
85  y[0] = x1 * w;
86  y[1] = x2 * w;
87 }
float t
RandScalar * implementation(void *t)
Definition: RandnScalar.cpp:17
contains the definition of a Vector type
A random number generator, uniform in the range 0-1.
Definition: RandScalar.h:29
void init()
Initialize the random generator using current time (time(0)).
Definition: RandScalar.cpp:57
double get()
Generate a random number from a uniform distribution.
Definition: RandScalar.cpp:44
Signal processing.
Definition: Image.h:22