gpt4 book ai didi

r - 编写调用 Fortran 库的 R 包

转载 作者:行者123 更新时间:2023-12-04 11:06:22 25 4
gpt4 key购买 nike

我正在尝试编写一个调用 Fortran 子例程的 R 包。我正在使用 Rstudio 包模板,它会自动创建一堆文件和目录。

./R/我有一个文件,Fpi.R

Fpi <- function(DARTS, ROUNDS) {
if (!is.loaded('Fpi')) {
dyn.load("./src/Fpi.so")
}
retvals <- .Fortran("pi", avepi = as.numeric(1), DARTS = as.integer(DARTS), ROUNDS = as.integer(ROUNDS))
return(retvals$avepi)
}

./src/我有 Fpi.f90
subroutine dboard(darts, dartsscore)
implicit none
integer, intent(in) :: darts
double precision, intent(out) :: dartsscore
double precision :: x_coord, y_coord
integer :: score, n

score = 0
do n = 1, darts
call random_number(x_coord)
call random_number(y_coord)

if ((x_coord**2 + y_coord**2) <= 1.0d0) then
score = score + 1
end if
end do

dartsscore = 4.0d0*score/darts

end subroutine dboard

subroutine pi(avepi, DARTS, ROUNDS)
implicit none
double precision, intent(out) :: avepi
integer, intent(in) :: DARTS, ROUNDS
integer :: MASTER, rank, i, n
integer, allocatable :: seed(:)
double precision :: pi_est, homepi, pirecv, pisum

interface
subroutine dboard(darts, dartsscore)
implicit none
integer, intent(in) :: darts
double precision, intent(out) :: dartsscore
end subroutine dboard
end interface

! we set it to zero in the sequential run
rank = 0
! initialize the random number generator
! we make sure the seed is different for each task
call random_seed()
call random_seed(size = n)
allocate(seed(n))
seed = 12 + rank*11
call random_seed(put=seed(1:n))
deallocate(seed)

avepi = 0
do i = 0, ROUNDS-1
call dboard(darts, pi_est)
! calculate the average value of pi over all iterations
avepi = ((avepi*i) + pi_est)/(i + 1)
end do
end subroutine pi

我还有 rstudio 生成的通用描述和命名空间文件。

我可以构建和加载库,但是当我尝试使用它时,出现此错误:
> library(MyPi)
> Fpi(DARTS = 100, ROUNDS = 100)
Error in .Fortran("pi", avepi = as.numeric(1), DARTS = as.integer(DARTS), :
"pi" not resolved from current namespace (MyPi)

我怎样才能解决这个问题?谢谢!

最佳答案

我只需要在我的 NAMESPACE 中添加一行

useDynLib(Fpi)

关于r - 编写调用 Fortran 库的 R 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31630345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com