2012-06-07 42 views
3

我正在使用f2py编译供Python脚本使用的数字模块。我减少了我的代码下面的小例子:子程序参数没有从Python正确传递到Fortran

fd.f:

module fd 
    ! Double precision real kind 
    integer, parameter :: dp = selected_real_kind(15) 

contains 

subroutine lprsmf(th) 
    implicit none 
    real(dp) th 
    write(*,*) 'th - fd',th 
end subroutine lprsmf 

end module fd 

itimes.f:

subroutine itimes(th) 
    use fd 
    implicit none 
    real(dp) th 

    write(*,*) 'th - it',th 
    call lprsmf(th) 
end subroutine itimes 

reprun.py:

import it 

th = 200 
it.itimes(th) 

的命令用于编译和运行如下(注意我在Windows下使用cmd):

gfortran -c fd.f 
f2py.py -c -m it --compiler=mingw32 fd.o itimes.f 
reprun.py 

输出是:

th - it 1.50520876326836550E-163 
th - fd 1.50520876326836550E-163 

我的第一个猜测是,th由于某种原因没有被正确地传递从reprun.py子程序itimes。但是,我不理解这种行为,因为完整版本的代码包含其他输入,所有这些都是正确传递的。从Fortran调用itime时,我无法让它做同样的事情,所以我假设它与Python/Fortran接口有关。任何人都可以提供有关这种行为发生的原因吗?

编辑:在reprun.py与th = 200.0更换th = 200产生以下的输出:

th - it 1.19472349365371216E-298 
th - fd 1.19472349365371216E-298 
+0

我对Python或f2py一无所知,但如果用th = 200.0替换th = 200,会发生什么? –

+0

@HighPerformanceMark,请参阅编辑。这仍然是一种垃圾价值,但是不同。 – astay13

回答

1

包装你itimes子程序模块中也是如此。这里是我做的:

itimes.f90:

module itime 

contains 

subroutine itimes(th) 
    use fd 
    implicit none 
    real(dp) th 

    write(*,*) 'th - it',th 
    call lprsmf(th) 
end subroutine itimes 

end module 

编译&运行:

gfortran -c fd.f90 
c:\python27_w32\python.exe c:\python27_w32\scripts\f2py.py -c -m it --compiler=mingw32 fd.f90 itimes.f90 

运行reprun.py:

import it 

th = 200 
it.itime.itimes(th) 

输出:

th - it 200.00000000000000  
th - fd 200.00000000000000  
+0

谢谢,这非常有帮助。 – astay13

+0

玩了一番,我发现我不需要itimes.f中的模块声明,似乎临界点是将fd.f90而不是fd.o传递给f2py。你知道这是为什么吗? – astay13

+0

@ astay13啊,你可能是对的,我只是改变了习惯。不确定,我只尝试将实际的Fortran源代码传递给f2py。我还会推荐总是将代码封装在模块中,这样可以避免很多Fortran陷阱。 – bananafish