Double precision complex in f2py

f2py and Complex*16 double precision

A subtle yet critical problem using double precision complex numbers can arise between Fortran and Python using f2py. f2py doesn’t seem to understand the kind parameters we specify when assigning a variable. 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.


Assuming the program has

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

Assign a double-precision complex variable like

complex(dp) :: x

Copy file .f2py_f2cmap into the top directory of your Python project (where is), containing:

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


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