I am playing around with f2py. I'm a bit confused about numpy intrinsic types vs. fortran 90 types. It seems like I can only use single precision reals in fortran 90, when interacting with python. Let me illustrate with an example:
Say I have this fortran 90 module, test.f90, to be compiled with f2py and imported in python:
module test
implicit none
integer, parameter :: sp = selected_real_kind(6,37) ! single precision
integer, parameter :: dp = selected_real_kind(15,307) ! double precision
real(sp) :: r_sp = 1.0
real(dp) :: r_dp = 1.0_dp
end module
and I compile like this:
f2py -c -m test test.f90
Then, in python:
>>> import test
>>> test.test.r_sp
array(1.0, dtype=float32)
>>> test.test.r_dp
array(1.0)
IOW, it seems like f2py doesn't accept double precision. This becomes even more problematic when passing input to a fortran 90 subroutine from python. Say I extend my module to:
module test
implicit none
integer, parameter :: sp = selected_real_kind(6,37) ! single precision
integer, parameter :: dp = selected_real_kind(15,307) ! double precision
real(sp) :: r_sp = 1.0
real(dp) :: r_dp = 1.0_dp
contains
subroutine input_sp(val)
real(sp), intent(in) :: val
real(sp) :: x
x = val
write(*,*) x
end subroutine
subroutine input_dp(val)
real(dp), intent(in) :: val
real(dp) :: x
x = val
write(*,*) x
end subroutine
end module
f2py -c -m test test.f90
python
>>> import test
>>> test.test.input_sp(array(1.0,dtype=float32))
1.0000000
>>> test.test.input_sp(array(1.0,dtype=float64))
1.0000000
>>> test.test.input_dp(array(1.0,dtype=float32))
-1.15948430791165406E+155
>>> test.test.input_dp(array(1.0,dtype=float64))
-1.15948430791165406E+155
So, it seems like any input variable to be sent from python must be declared single precision. Is this a known issue with f2py?
Also, as a follow up question: Converting from sp to dp works, in the following sense:
subroutine input_sp_to_dp(val)
real(sp), intent(in) :: val(2)
real(dp) :: x(2)
x = val
write(*,*) x
end subroutine
But I wonder if this is compiler specific at all? Can I expect the above subroutine to do the right thing with any compiler on any architecture? When testing, I used gfortran fro all the above examples.
See Question&Answers more detail:
os