![](/img/trans.png)
[英]Friends-of-friends algorithm written in Python need to be in Fortran 90/95
[英]making python and fortran friends
假設我們需要在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
並以這種方式在python中調用它:
import modulename
a = 2.0
b = 0.0
b = modulename.pow2(a, b)
給我們工作的結果。 我可以用其他方式調用fortran函數,因為我認為第一種方式有點笨拙嗎?
我認為你只需稍微改變你的f2py函數簽名(這樣out_x
只是intent(out)
而in_x
只是intent(in)
):
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
!f2py real, intent(in) :: in_x
real, intent(out) :: out_x
!f2py real, intent(out) :: out_x
out_x = in_x ** 2
return
end subroutine pow2
現在編譯:
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
跑:
>>> import test2
>>> test2.pow2(3) #only need to pass intent(in) parameters :-)
9.0
>>>
避免intent(inout)
參數的另一個好處是(有一些其他限制),結果函數可以被認為是PURE
。 這與函數式語言采用的無副作用方法有關,並且通過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
然后只需在代碼中使用此函數(無需其他導入)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.