1

This question applies to Fortran, more precisely the compiler gfortran.

I need to know how I can convert a real(kind=8) array to a real(kind=4) array such that all reasonable digits in each entry of the array remain.

Obviously, a type cast from kind=8 to kind=4 implies a loss of information. Hence, what I am looking for is the proper way to lose just as much information as necessary - but not more.

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
Coffee
  • 11
  • 5
  • 3
    Can you give examples to show why you think gfortran (or any compiler) is throwing away more information than necessary when changing kind parameter? – francescalus Jul 30 '21 at 16:47
  • Your comment made me think, francescalus. I think there is no reason to believe that more information than necessary is lost, when one casts real(kind=8) to real(kind=4) variables. – Coffee Aug 04 '21 at 10:54
  • My problem is different from what I thought, see below. – Coffee Aug 04 '21 at 10:55

1 Answers1

6

The conversion to real is done using the real() intrinsic function. The optional kind= argument specifies the kind of the result.

If you truly need the result to be kind 4, you use

 real(x, 4)

and you can do whatever you want with the result. For example, assign it to a variable.

You will get the same result with an implicit conversion, but the explicit conversion shows the intent and also avoids certain compiler warnings about a possible loss of precision.

As always:

  1. It is better to use named constants for your kind parameters so that you can change it everywhere easily.

  2. Using kind numbers as literal constants like 4 or 8 is not portable and is really ugly. Fortran 90 kind parameter

  • clarification to the last point: a simple assignment would also do the trick. Assume `x` is of type `REAL` and `y` is of type `DOUBLE PRECISION`, you can just do `x=y`. the conversion is done implicitly (however, this hides the conversion, and writing things out makes the intent of the code readable). You can also write `x=real(y,kind(x))` – kvantour Jul 31 '21 at 12:12
  • Dear Vladimir F and kvantour. Thank you for your explanations, these made me smarter. As a result, I now do all type conversions explicitly, in order to convey my intent. I do indeed need real(kind=4) variables in order to get an old plotting library work (PGPLOT). My first thought was that the type conversion must be wrong. Instead, I am using FFTPACK5.1, which does not adapt properly to the -fdefault-real-8 compiler option, because all kind declarations are explicit in FFTPACK5.1. The erroneous behaviour of my code stems from the fact that I falsely assumed FFTPACK5.1 to adapt generically... – Coffee Aug 04 '21 at 11:00
  • ...to the -fdefault-real-8 compiler option. – Coffee Aug 04 '21 at 11:01