在循环中使用一组随机数生成器

Using a single set of random number generators in a loop

给出下面的代码,是否可以修改它,以便 xy 有一组 M “随机”数字,它们将“重新启动” i?

每次迭代的集合的开头

我知道我能做的是为 xy 预先生成一个长度为 M 的数组,但由于内存有限,我不能使用数组。我正在考虑以某种方式使用带有种子的随机数,但一直无法弄清楚。

double sampleNormal()
{
   double u = ((double) rand() / (RAND_MAX)) * 2 - 1;
   double v = ((double) rand() / (RAND_MAX)) * 2 - 1;
   double r = u * u + v * v;
   if (r == 0 || r > 1) return sampleNormal();
   double c = sqrt(-2 * log(r) / r);
   return u * c;
}

...

double x = 0;
double y = 0;
double a = 0;
double f = 100e6;
double t = 0;
double fsamp = 2e9;

for(int i = 0; i < N; i++)
{
    for(int j = 0; j < M; j++)
    {
        x = sampleNormal();
        y = sampleNormal();
        t = j/fsamp;

        a = x*cos(2*pi*f*t)+y*sin(2*pi*f*t);
    }
}

that will "restart" at the beginning of the set for every iteration of i

was thinking of using random numbers with seeds somehow but haven't been able to figure it out.

代码可能会被滥用 srand()

// Get some state info from rand() for later.
unsigned start = rand();
start = start*(RAND_MAX + 1u) + rand();

for(int i = 0; i < N; i++) {
  // Initialize the random number generator to produce the same sequence.
  srand(42);  // Use your favorite constant.
  for(int j = 0; j < M; j++) {
    x = sampleNormal();
    y = sampleNormal();
    t = j/fsamp;

    a = x*cos(2*pi*f*t)+y*sin(2*pi*f*t);
  }
}

// Re-seed so other calls to `rand()` are not so predictable.
srand(start);