YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
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
9#include <yarp/sig/Vector.h>
10#include <ctime>
11#include <cstdio>
12#include <cmath>
13
14using namespace yarp::sig;
15using namespace yarp::math;
16
18{
19 return static_cast<RandScalar*>(t);
20}
21
23{
24 impl = new RandScalar;
25 init();
26}
27
29{
30 impl = new RandScalar;
31 init(seed);
32}
33
35{
36 delete (implementation(impl));
37}
38
39// initialize with a call to "time"
41{
42 // initialize with time
43 int t=(int)time(nullptr);
45}
46
48{
49 //force re-execution of BoxMuller
50 executeBoxMuller = true;
51 seed=s;
52 implementation(impl)->init(s);
53}
54
55double 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
71void 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)
contains the definition of a Vector type
A random number generator, uniform in the range 0-1.
Definition RandScalar.h:27
void init()
Initialize the random generator using current time (time(0)).
double get()
Generate a random number from a uniform distribution.
double get(double u=0.0, double sigma=1.0)
Generate a randomly generated number, drawn from a normal distribution.
RandnScalar()
Constructor.
void init()
Initialize the generator.