Beginner Q: real number precision when reading in data

Ok, so, I have this code:

program main
    integer, parameter :: dp = selected_real_kind(15, 307)
    real(kind=dp) number
    number = 1.2
    write(*,*) number
end program

this outputs:

1.2000000476837158

Am I doing something wrong here? Why am I not seeing my desired precision getting written out?

I know I can specify _dp on my number like this:

program main
    integer, parameter :: dp = selected_real_kind(15, 307)
    real(kind=dp) number
    number = 1.2_dp
    write(*,*) number
end program

And that will output 1.2000000000000000, which is what I want. But what if I am reading data in from a file? How do I tack on the _dp onto a value I read in from a file?

Sorry, have not read the original post properly.

I/O works differently from assignments. You cannot tack a _dp to a value in a file because dp is a local parameter, and the file cannot know (or care) how your local parameters are defined. The compiler, in contrast, does know what the parameter constant _dp means, so you can use it to specify the kind of your literal constants.

ah. Ok, I see what you mean. I do find it weird though, needing to tack on the _dp in code when my number is already specified as dp in the declaration.

I should have said something about that too. Your expression is a shorthand way of saying:

That is, the expression on the right is evaluated in default floating point precision, and then converted for the assignment to the extended precision. What you really want is for the expression to be evaluated in the extended precision in the first place, and then just transferred to the lhs during the assignment. That is what your second expression in your post accomplishes.

1 Like

Fortran principle : The right hand (side) does not know what the left hand (side) is doing.

Pros: the meaning of an expression can be determined without context. This helps programmer and compiler.

Cons: some meanings require more characters of source.

3 Likes