简体   繁体   English

使用 pracma fzero function 在 R 中查找根

[英]Root finding in R using pracma fzero function

I am working with this code to find the roots of the equation using pracma fzero function.我正在使用此代码使用 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.我使用普通的 for 循环得到 output。 But when using the parallel for loop, I get this error.但是当使用并行 for 循环时,我得到了这个错误。

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.我不知道如何解决这个错误。

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.当您使用 PSOCK 集群时,它会使用 Rscript 启动独立的 R 进程,因此您需要告诉它们加载必要的包。 Explicitly naming the package like pracma::fzero works or foreach has an argument .packages :明确命名 package 就像pracma::fzero工作或foreach有一个参数.packages

.packages character vector of packages that the tasks depend on. .packages 任务所依赖的包的字符向量。 If ex requires a R package to be loaded, this option can be used to load that package on each of the workers.如果 ex 需要加载 R package,则可以使用此选项将 package 加载到每个 worker 上。 Ignored when used with %do%.与 %do% 一起使用时被忽略。

If you use foreach(i=1:n, .packages = c("pracma")) it works as well.如果您使用foreach(i=1:n, .packages = c("pracma"))它也能正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM