Home > Blockchain >  Root finding in R using pracma fzero function
Root finding in R using pracma fzero function

Time:10-02

I am working with this code to find the roots of the equation using pracma fzero function.

library(doParallel)
library(pracma)

n <- 2

root <- function(x) {
   return(x**2 5*x 6)
}

result1 = foreach(i=1:n) %do% fzero(root,i) #Normal for loop

print("Normal Loop completed.")

myCluster <- makeCluster(4, type = "PSOCK") 
registerDoParallel(myCluster)

result2 = foreach(i=1:n) %dopar% fzero(root,i) #Parallel for loop

print("Parallel Loop completed.")

stopCluster(myCluster)

I get the output using normal for loop. But when using the parallel for loop, I get this error.

Error in fzero(root, i): task 1 failed - "could not find function "fzero""
Traceback:

1. foreach(i = 1:n) %dopar% fzero(root, i)
2. e$fun(obj, substitute(ex), parent.frame(), e$data)

I don't know how to solve this error.

CodePudding user response:

When you use a PSOCK cluster, it starts up independent R processes using Rscript, so you need to tell them to load the requisite packages. Explicitly naming the package like pracma::fzero works or foreach has an argument .packages:

.packages character vector of packages that the tasks depend on. If ex requires a R package to be loaded, this option can be used to load that package on each of the workers. Ignored when used with %do%.

If you use foreach(i=1:n, .packages = c("pracma")) it works as well.

  •  Tags:  
  • r
  • Related