2015-10-06 161 views
0

我有一个两部分的问题,可能会刷首选的习惯,以及我是否不必要地复杂的问题。我一直在使用.C并学会了。呼叫做R的繁重工作。我想和.Fortran做一个比较,所以我一直在学习它。因此,我的问题可能是由于我有限的Fortran知识。调用.R从功能辅助功能

在R中有几个函数我想转换到Fortran,彼此相关。我没有把这个问题的细节散列出来,而是创造了一个不太实用的例子,但这是一个很好的例子。

我有两个函数和两个相关子找到幅度和平方大小,这使得该文件的全部内容:

! Actual functions 
    real function sumofsquaresfun (x,y) 
    implicit none 
    real :: x,y 
    sumofsquaresfun=x*x+y*y 
    end function sumofsquaresfun 


    real function magnitudefun(x,y) 
    implicit none 
    real :: x,y,tmp 
    tmp=sumofsquaresfun(x,y) 
    magnitudefun=sqrt(tmp) 
    end function magnitudefun 

! Wrappers for R accessibility since R requires subroutines 
    subroutine sumofsquares(x,y,answer) 
    implicit none 
    real :: x,y 
    real answer 
    answer=sumofsquaresfun(x,y) 
    end subroutine sumofsquares 

    subroutine magnitude(x,y,answer) 
    implicit none 
    real :: x,y 
    real answer 
    answer=magnitudefun(x,y) 
    end subroutine magnitude 

假设我中的R是两个子程序是有用的,所以保持两者分离很重要。

当我尝试牛逼编译使用

R CMD SHLIB fortrancode.f95 

我有几个错误相同的两类错误:

Error: Return type mismatch of function 'sumofsquaresfun' at (1) (UNKNOWN/REAL(4)) 

Error: Function 'sumofsquaresfun' at (1) has no IMPLICIT type 

我的问题的重要性排列:

  1. 即使可行,这是解决这个问题的首选方法吗?我应该使用模块吗?我已经看到这个讨论(using a Fortran module in R?)和相关的一个由相同的OP,但不知道涉及模块是否必要/最优。
  2. 如果我想要做的是正确的方法,是什么导致了这些令人尴尬的错误?
  3. 我喜欢使用函数,因为这就是他们的意思,但是我是否通过创建子例程包装太过纯粹主义?抛弃它们是否更好,所以我只有两个子程序?

非常感谢!

回答

0

这是一个比R问题更多的Fortran问题。 您尚未在子例程中声明函数。 这样做,它应该编译。

! Actual functions 
real function sumofsquaresfun (x,y) 
    implicit none 
    real :: x,y 
sumofsquaresfun=x*x+y*y 
end function sumofsquaresfun 


real function magnitudefun(x,y) 
    implicit none 
    real :: x,y,tmp 
    real sumofsquaresfun 
    tmp=sumofsquaresfun(x,y) 
    magnitudefun=sqrt(tmp) 
end function magnitudefun 

! Wrappers for R accessibility since R requires subroutines 
subroutine sumofsquares(x,y,answer) 
    implicit none 
    real :: x,y 
    real answer 
    real sumofsquaresfun 
    answer=sumofsquaresfun(x,y) 
end subroutine sumofsquares 

subroutine magnitude(x,y,answer) 
    implicit none 
    real :: x,y 
    real answer 
    real magnitudefun 
    answer=magnitudefun(x,y) 
end subroutine magnitude 

警告:您正在使用real但不要忘了,R使用双精度。 real是单精度。你应该使用类似real*8Fortran95的东西。

+0

感谢您的回应,它确实使代码工作。我不确定是否我一次提出太多问题以切实期待对其他风格问题的回答。 – Zenos