048. cmplx
should be used with a kind
argument#
topic: Data types
cmplx(x, y [, kind])
returns a single precision complex variable,
even if x
and y
are double precision, unless a kind
is specified.
program test_cmplx
implicit none
integer, parameter :: dp = kind(0.0d0)
complex, parameter :: c1 = (1.0, 1.0)
complex, parameter :: c2 = (1.0d0, 1.0d0)
complex(kind=dp), parameter :: c3 = (1.0d0, 1.0d0)
! Parameter
print *, kind(c1) ! 4
print *, kind(c2) ! 4
print *, kind(c3) ! 8
print *
! Inline literal
print *, kind((1.0, 1.0)) ! 4
print *, kind((1.0, 1.0d0)) ! 8
print *, kind((1.0d0, 1.0)) ! 8
print *, kind((1.0d0, 1.0d0)) ! 8
print *
! Calling `cmplx`
print *, kind(cmplx(1.0d0, 1.0d0)) ! 4 -- likely unintended!
print *, kind(cmplx(1.0d0, 1.0d0, kind=dp)) ! 8
print *
! Same if passing real component only
print *, kind(cmplx(1.0d0)) ! 4
print *, kind(cmplx(1.0d0, kind=dp)) ! 8
print *
end program test_cmplx
4
4
8
4
8
8
8
4
8
4
8
Some further references:
CMPLX(X,Y,[KIND]) returns a single precision complex variable, even if X and Y are double precision, unless a KIND is specified.
— FortranTip (@fortrantip) December 25, 2021
Merry Christmas and Happy Holidays! Posts may be sparse until the new year. pic.twitter.com/MD9tCw4pTB
- 1
Compiled using
GNU Fortran (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
with no flags