2

I'm just taking my first steps with the package parallel and the foreach() function. therefore this question will be rather stupid. so here's my task i want to fullfil:

  1. apply function to an object t
  2. use the outcome in the next iteration

a simple example would be:

newFunc<-function(){
    test[i+1] <<- sqrt(test[i])
}

test <- c(1,rep(NA, 10))

foreach(i=1:11, .combine='rbind', .export='test')%do% newFunc()

this yields me a vector of ones as a for-loop would of course as well. however, if i try parallelise this this yields a different outcome:

test <- c(1,rep(NA, 10))

library(doParallel)
library(foreach)
cl <- makeCluster(4)
registerDoParallel(cl)

foreach(i=1:11, .combine='rbind', .export='test')%dopar% newFunc()

stopCluster(cl)

this leaves me with the output c(1, NA, NA, NA, NA, ..., NA). I guess this is because the slaves don't know the result of other functions? I hope I supplied the necessary information. My actual function is of course more complex, yet this example seemed the easiest way do demonstrate my problem.

edit: I guess the first question is: can such a problem be parallelised at all?

4

1 回答 1

2

确实,所提出的迭代不会并行运行,但是

test = numeric(11); test[] = 2
test^(1/2^(0:10))

是您感兴趣的解决方案。这很容易并行化(尽管没有必要,因为计算已经矢量化)

fun = function(i, test)
    test[i] ^ (1 / 2^(i - 1))
unlist(mclapply(seq_along(test), fun, test))

对于并行评估,fun不应更新非局部变量(如使用<<-)。也许您的真正问题可以以允许并行评估的方式提出,即使原始公式似乎需要顺序评估?

于 2012-09-15T15:42:27.160 回答