gpt4 book ai didi

multithreading - 使用OpenMP使用已知种子生成随机数的安全方法是什么?

转载 作者:行者123 更新时间:2023-12-03 13:16:31 27 4
gpt4 key购买 nike

我正在寻找一种方法,可以在已知输入种子的同时与OpenMP并行安全地生成随机数。我搜索并以OMPRNG结尾。使用我可以手动编写代码的程序包还有其他方法吗?
另外,我想提及的是,我需要这些随机数来进行monto Carlo积分。

最佳答案

在蒙特卡洛模拟的上下文中,您可以使用rand_r。从这个SO Thread可以读取:

I think you're looking for rand_r(), which explicitly takes thecurrent RNG state as a parameter. Then each thread should have it'sown copy of seed data (whether you want each thread to start off withthe same seed or different ones depends on what you're doing, here youwant them to be different or you'd get the same row again and again).


实际上,这是在此 SO Thread中并行执行蒙特卡罗模拟的函数,实际上产生了良好的结果。该答案中的代码:
int main(void)
{
double start = omp_get_wtime();
long points = 1000000000; //....................................... INPUT AVOIDED
long m = 0;
unsigned long HAUSNUMERO = 1;
double DIV1byMAXbyMAX = 1. / RAND_MAX / RAND_MAX;

int threads = get_nprocs();
omp_set_num_threads(threads);
#pragma omp parallel reduction (+: m )
{
unsigned int aThreadSpecificSEED_x = HAUSNUMERO + 1 + omp_get_thread_num();
unsigned int aThreadSpecificSEED_y = HAUSNUMERO - 1 + omp_get_thread_num();
#pragma omp for nowait
for(long i = 0; i < points; i++)
{
double x = rand_r( &aThreadSpecificSEED_x );
double y = rand_r( &aThreadSpecificSEED_y );
m += (1 >= ( x * x + y * y ) * DIV1byMAXbyMAX);
}
}
double end = omp_get_wtime();
printf("%f\n",end-start);
printf("Pi is roughly %lf\n", (double) 4*m / (double) points);
}
从评论部分( Sam Manson)引用:

Might be worth noting that rand_r only has an int for state (i.e.likely 32bits), so the entire space could get exhausted pretty quicklyduring a large MC run. 128 bits of state seems more reasonable, whichwould necessitate some other algorithm (e.g. PCG-64 or xoroshiro128)

关于multithreading - 使用OpenMP使用已知种子生成随机数的安全方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66668840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com