Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
结交python和fortran的朋友_Python_Fortran_F2py - Fatal编程技术网

结交python和fortran的朋友

结交python和fortran的朋友,python,fortran,f2py,Python,Fortran,F2py,假设我们需要在python程序中调用fortran函数,该函数返回一些值。我发现以这种方式重写fortran代码: subroutine pow2(in_x, out_x) implicit none real, intent(in) :: in_x !f2py real, intent(in, out) :: out_x real, intent(out) :: out_x out_x = in_x ** 2 ret

假设我们需要在python程序中调用fortran函数,该函数返回一些值。我发现以这种方式重写fortran代码:

subroutine pow2(in_x, out_x)
      implicit none
      real, intent(in)      :: in_x
!f2py real, intent(in, out) :: out_x
      real, intent(out)     :: out_x
      out_x = in_x ** 2
      return
end
import modulename
a = 2.0
b = 0.0
b = modulename.pow2(a, b)
并以python的方式调用它:

subroutine pow2(in_x, out_x)
      implicit none
      real, intent(in)      :: in_x
!f2py real, intent(in, out) :: out_x
      real, intent(out)     :: out_x
      out_x = in_x ** 2
      return
end
import modulename
a = 2.0
b = 0.0
b = modulename.pow2(a, b)

给我们工作的结果。我可以用另一种方式调用fortran函数吗,因为我认为第一种方式有点笨拙?

我认为您只需要稍微更改f2py函数签名(这样
out\ux
仅为
intent(out)
,而
in\ux
仅为
intent(in)
):

现在编译:

f2py -m test -c test.f90
现在运行:

>>> import test
>>> test.pow2(3)   #only need to pass intent(in) parameters :-)
9.0
>>>

请注意,在这种情况下,
f2py
能够正确扫描函数的签名,而无需特殊的
!f2py
注释:

!test2.f90
subroutine pow2(in_x, out_x)
  implicit none
  real, intent(in)   :: in_x
  real, intent(out)     :: out_x
  out_x = in_x ** 2
  return
end subroutine pow2
汇编:

f2py -m test2 -c test2.f90
运行:


避免
intent(inout)
参数的另一个好处是(有一些其他限制)结果函数。这与函数式语言所采用的无副作用方法有关,并通过Fortran编译器进行更好的优化和错误检测来获得回报,对于自动并行化尤其重要。

如果您使用的是IPython,请尝试使用magic命令,这使它能够编写

%%fortran
subroutine pow2(in_x, out_x)
  implicit none
  real, intent(in)   :: in_x
  real, intent(out)     :: out_x
  out_x = in_x ** 2
  return
end subroutine pow2

然后只需在代码中使用此函数(无需额外导入)。

它如何帮助我?据我所知,这是一种升级的交互模式。它还允许您与其他程序(如R、MATLAB和FORTRAN)进行交互。看看你有什么问题吗?你想怎么称呼它?@mgilson我想在某些情况下,我需要以上述方式更新大量fortran代码,但我不想这样做,因为我没有疯,也没有时间这么做。哇,太棒了!这种方法甚至可以返回元组中的多个变量!只是出于好奇,如果还有其他一些技巧,我现在就不勾选这个答案。我经常被用
f2py
包装fortran代码是多么容易给人留下深刻印象。正因为如此,我从未费心学习过任何pythoncapi,甚至是Cython,尽管在某些时候我想学习这些技能。