编写调用Fortran库的R包

4
我正在尝试编写一个调用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生成的通用DESCRIPTION和NAMESPACE文件。

我可以构建和加载库,但在尝试使用它时,我会遇到以下错误:

> 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)

我该怎么修复这个问题?谢谢!

Fortran距离60岁只有两年的时间了。也许现在是考虑重构的时候了? - Brandon Bertelsen
7
@BrandonBertelsen 我没有使用Fortran穿孔卡,或许你应该考虑一下看看Fortran 2008?我有几个使用它的好理由,但这不是问题的主题。 - Ignacio
我只是在调皮捣蛋。 - Brandon Bertelsen
5
@BrandonBertelsen,你开玩笑,但是Fortran仍然是计算科学(与计算机科学相对)中首选的语言之一。 - Hong Ooi
1个回答

3
我只需要在我的命名空间中添加一行代码。
useDynLib(Fpi)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接