drjrm3
drjrm3

Reputation: 4718

How to cast a real as a specific KIND?

I have multiple kinds I am using in Fortran and would like to add a real valued number where the real number is cast as that kind.

For example, something like:

program illsum
    implicit none

#if defined(USE_SINGLE)
    integer, parameter :: rkind = selected_real_kind(6,37)
#elif defined(USE_DOUBLE)
    integer, parameter :: rkind = selected_real_kind(15,307)
#elif defined(USE_QUAD)
    integer, parameter :: rkind = selected_real_kind(33, 4931)
#endif

    integer :: Nmax = 100 
    integer :: i

    real(kind = rkind) :: mysum = 0.0 

    do i = 1,Nmax
        mysum = mysum + kind(rkind, 1.0)/kind(rkind, i)
    enddo

end program illsum

So I want to make sure that 1.0 and the real valued expression of i are expressed as the proper kind that I have chosen before performing the division and addition.

How can I cast 1.0 as rkind?

Upvotes: 1

Views: 382

Answers (1)

francescalus
francescalus

Reputation: 32366

To convert a numeric value to a real value then there is the real intrinsic function. Further, this takes a second argument which determines the kind value of the result. So, for your named constant rkind

real(i, rkind)      ! Returns a real valued i of kind rkind
real(1.0, rkind)    ! Returns a real valued 1 of kind rkind

which I think is what you are meaning with kind(rkind, 1.0). kind itself, however, is an intrinsic which returns the kind value of a numeric object.

However, there are other things to note.

First, the literal constant 1._rkind (note the . in there, could be clearer with 1.0_rkind) which is of kind rkind and value approximating 1.

There's no comparable expression i_rkind, though, so the conversion above would be necessary for a real result of kind rkind with value approximating i.

That said, for you example there is no need to do such casting of the integer value. Under the rules of Fortran the expression 1._rkind/i involves that implicit conversion of i and is equivalent to 1._rkind/real(i,rkind) (and real(1.0, rkind)/real(i,rkind)).

Upvotes: 3

Related Questions