Getting "-nan (ind)" while trying to create random variations

I am trying to generate random variations, trying to generate two standard normal values ​​r1, r2 using polar coordinates along with the average value and the sigma value. However, when I run my code, I keep getting "-nan (ind)" as my output.

What am I doing wrong here? The code is as follows:

static double saveNormal;
static int NumNormals = 0;
static double PI = 3.1415927;

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

static double normal(double r, double mean, double sigma) {
    double returnNormal;
    if (NumNormals == 0) {
        //to get next double value
        double r1 = fRand(0, 20);
        double r2 = fRand(0, 20);
        returnNormal = sqrt(-2 * log(r1)) * cos(2 * PI*r2);
        saveNormal = sqrt(-2 * log(r1)) * sin(2 * PI*r2);
    }
    else {
        NumNormals = 0;
        returnNormal = saveNormal;
    }
    return returnNormal*sigma + mean;
}
+4
source share
2 answers

So, you use the Box-Muller method to pseudo-randomly select a random random variable. For this transformation to work, r1it r2must be evenly distributed independently of each other in [0,1].

r1/r2 [0,20], sqrt, a > 1, nans.

double r1 = fRand(0, 1);
double r2 = fRand(0, 1);

, ++ 11 <random> ; fRand - rand() -to- double . , .

FYI, , ++ 11

#include <random>
#include <iostream>

int main()
{
  auto engine = std::default_random_engine{ std::random_device{}() };
  auto variate = std::normal_distribution<>{ /*mean*/0., /*stddev*/ 1. };

  while(true) // a lot of normal samples ...
    std::cout << variate(engine) << std::endl;
}
+3

r1 , log(r1) undefined.


, rand(), , , . <random>

+1

Source: https://habr.com/ru/post/1689300/


All Articles