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