Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve precision on variables defined by integer quotient

Say I have the following program:

program derp
    implicit none
    integer, parameter :: ikind = selected_real_kind(18)
    real (kind = ikind) :: a = 2.0 / 3.0
    print*, a
end program derp

The program derp outputs 0.6666666865348815917, which is clearly not 18 digits of precision. However, if I define a=2.0 and b=3.0 using the same method and then define c=a/b I get an output of 0.666666666666666666685, which is good. How do I just define a variable as a quotient of integers and have it store all the digits of precision I want from selected_real_kind?

like image 237
Mr. G Avatar asked May 10 '13 00:05

Mr. G


1 Answers

Try: real (kind = ikind) :: a = 2.0_ikind / 3.0_ikind

The reason is while the LHS is high precision, the RHS in your code example, 2.0 / 3.0, is not. Fortran does that calculation in single precision and then assigns the result to the LHS. The RHS side isn't calculated in higher precision because the LHS is high precision. digits_kind is the way of specifying the type of a constant digits.

like image 122
M. S. B. Avatar answered Sep 18 '22 04:09

M. S. B.