Double precision complex in f2py

f2py and Complex*16 double precision

You may run into a subtle yet critical problem using double precision complex numbers between Fortran and Python using f2py. The real issue is that f2py doesn’t seem to understand the kind parameters we specify when assigning a variable. So f2py assumes your complex numbers are single precision (8 bytes per complex number) instead of double precision (16 bytes per complex number).

You won’t get an error on compiling, but your Python program importing the Fortran .so module will give erroneous results.

Solution

Assuming you have in your Fortran code

use, intrinsic :: iso_c_binding, only: sp=>C_FLOAT, dp=>C_DOUBLE

and that you assign your double-precision complex variable like

complex(dp) :: x

then you just copy a file .f2py_f2cmap into the top directory of your Python project (where setup.py is) with the following contents:

dict(real= dict(sp='float', dp='double'),
complex = dict(sp='complex_float',dp="complex_double"))

Notes

At this time it appears we don’t use the C_DOUBLE_COMPLEX from iso_c_binding, I notice that F90Wrap does the same.

Leave a Comment