foreach,doParallel和随机生成 [英] foreach, doParallel and random generation

查看:187
本文介绍了foreach,doParallel和随机生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑使用并行foreach来生成随机值的最基本(效率低下)的代码:

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.

推荐答案

您的担心是正确的;随机数生成不能神奇地并行工作,需要采取进一步的措施.使用foreach框架时,可以使用 doRNG 扩展名来确保声音随机并行执行时也会编号.

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.

示例:

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)

这篇关于foreach,doParallel和随机生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆