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



给定下面的代码,是否可以修改它,使其具有单个M"随机";用于CCD_ 2和CCD_;重新启动";在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);
}
}

将"重新启动";在i 的每次迭代的集合的开头

曾想过以某种方式使用带有种子的随机数,但一直未能解决。

代码可能会滥用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);

最新更新