foreach, doParallel and random generation

你说的曾经没有我的故事 提交于 2019-12-08 03:57:09

问题


Consider the very basic (and inefficient) code using parallel foreach for generating random values:

cl <- makeCluster(2)
registerDoParallel(cl)
foreach(i = 1:100) %dopar% rnorm(1)

Is it correct or are there any additional steps needed for random generation to work properly? I guess it's enough and fast checks seem to "prove" that seeds work properly, but I'd like to be sure that it is so on other platforms, since I want the code to be portable.


回答1:


Your worries are correct; random number generation does not magically work in parallel and further steps need to be taken. When using the foreach framework, you can use the doRNG extension to make sure to get sound random numbers also when done in parallel.

Example:

library("doParallel")
cl <- makeCluster(2)
registerDoParallel(cl)

## Inject the doRNG framework to above registered for each backend
library("doRNG")
registerDoRNG()

foreach(i = 1:100) %dopar% rnorm(1)


来源:https://stackoverflow.com/questions/43299428/foreach-doparallel-and-random-generation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!