mirror of
https://git.rwth-aachen.de/acs/public/villas/node/
synced 2025-03-09 00:00:00 +01:00
Added Box-Muller method to generate normal distributed RV
This commit is contained in:
parent
68648f03a1
commit
82a1b36820
2 changed files with 43 additions and 0 deletions
|
@ -81,6 +81,17 @@ struct timespec;
|
|||
*/
|
||||
extern pthread_t _mtid;
|
||||
|
||||
/** Normal random variate generator using the Box-Muller method
|
||||
*
|
||||
* @param m Mean
|
||||
* @param s Standard deviation
|
||||
* @return Normal variate random variable (Gaussian)
|
||||
*/
|
||||
double box_muller(float m, float s);
|
||||
|
||||
/** Double precission uniform random variable */
|
||||
double randf();
|
||||
|
||||
/** Safely append a format string to an existing string.
|
||||
*
|
||||
* This function is similar to strlcat() from BSD.
|
||||
|
|
|
@ -27,6 +27,38 @@
|
|||
|
||||
pthread_t _mtid;
|
||||
|
||||
double box_muller(float m, float s)
|
||||
{
|
||||
double x1, x2, y1;
|
||||
static double y2;
|
||||
static int use_last = 0;
|
||||
|
||||
if (use_last) { /* use value from previous call */
|
||||
y1 = y2;
|
||||
use_last = 0;
|
||||
}
|
||||
else {
|
||||
double w;
|
||||
do {
|
||||
x1 = 2.0 * randf() - 1.0;
|
||||
x2 = 2.0 * randf() - 1.0;
|
||||
w = x1*x1 + x2*x2;
|
||||
} while (w >= 1.0);
|
||||
|
||||
w = sqrt(-2.0 * log(w) / w);
|
||||
y1 = x1 * w;
|
||||
y2 = x2 * w;
|
||||
use_last = 1;
|
||||
}
|
||||
|
||||
return m + y1 * s;
|
||||
}
|
||||
|
||||
double randf()
|
||||
{
|
||||
return (double) random() / RAND_MAX;
|
||||
}
|
||||
|
||||
void die()
|
||||
{
|
||||
if (pthread_equal(_mtid, pthread_self()))
|
||||
|
|
Loading…
Add table
Reference in a new issue