2

I can cast a double precision real variable into single precision using sngl. But how can I cast a double precision complex variable into a single precision one?

DaPhil
  • 1,509
  • 4
  • 25
  • 47

2 Answers2

8

Use the generic REAL() for all real numbers conversions, although SNGL() can be used too for one specific case:

  integer, parameter :: sp = kind(1e0), dp = kind(1d0)

  real(x)  !converts to the default kind, which is the single precision
           !sngl(x) does the same thing
  real(x, sp) ! converts to the kind sp (single precision)
  real(x, dp) ! converts to the kind dp (double precision)

with complex it is the same, but use CMPLX():

  cmplx(x)  !converts to the default kind, which is the single precision
  cmplx(x, sp) ! converts to the kind sp (single precision)
  cmplx(x, dp) ! converts to the kind dp (double precision)

On assignment the conversion is implicit and you do not have to (but can) use these explicit conversion functions.

The whole concept of single precision and double precision is somewhat obsolete and was superseded by Fortran 90 kinds.

Community
  • 1
  • 1
-2

You can make a copy in a single precision complex variable, or you can also use the cmplx and dcmplx functions:

program test
  complex*16:: a
  complex   :: b
  a = (1.d0, 2.d0)
  b = a

  print *,  a, b
  print *,  cmplx(a), dcmplx(b)
end

output:

 (1.00000000000000,2.00000000000000) (1.000000,2.000000)
 (1.000000,2.000000) (1.00000000000000,2.00000000000000)
Anthony Scemama
  • 1,563
  • 12
  • 19
  • 3
    I have to say that nowadays I would much prefer Valdimir's solution, and also I ought to note that complex*16 is not standard Fortran - again the kinds mechanism addresses this in moder Fortran – Ian Bush Nov 14 '14 at 15:05