user15964
user15964

Reputation: 2639

Precision and kind in cmplx()

According to the documentation.

cmplx(x,y) gives single precision by default.

But it has kind parameter

CMPLX( x, y, kind) has the complex value whose real part is REAL( x, kind) and whose imaginary part is REAL( y, kind).

But I tried this

print*,cmplx(1.12,2.34,kind(0D0))

it gives

(1.12000000476837,2.33999991416931)

it is complex(8), but the precision is lost.

Although I know in this case, I can simply use (1.12D0,2.23D0). But I am wondering what the point of kind in cmplx?

Upvotes: 1

Views: 767

Answers (1)

M. S. B.
M. S. B.

Reputation: 29401

The problem is that the constants are single precision even though they are used to define a double-precision variable. You need to specify the precision of the constants. The following example program uses the kind real64, which means 64 bits (i.e., double precision), from the ISO Fortran environment of Fortran 2003 to show this:

program test

   use, intrinsic :: ISO_FORTRAN_ENV

   print*,cmplx(1.12,2.34,kind(0D0))
   print*,cmplx(1.12_real64,2.34_real64,kind(0.0_real64))

end program test

Which you achieved with 1.23D0, 2.34D0. The kind option would be useful in other contexts, e.g., changing the type of a variable being passed to a subroutine to match the expected argument: call SomeSub ( cmplx (1.12, 2.34, kind (0D0) ) would match the argument of a subroutine SomeSub that expected a double-precision complex argument.

Upvotes: 2

Related Questions