How can i get up to 7 significant figures of my result in FORTRAN90?
-
03-06-2021 - |
Question
INTEGER, PARAMETER :: SINGLE=SELECTED_REAL_KIND(7)
REAL(KIND=SINGLE) :: K
REAL::X
...
K=X
WRITE(*,*) K
When i write 5 or 6 inside SELECTED_REAL_KIND
, it outputs six significant figures but when i try 7, it outputs more than 7. Can you tell me why? Where i got it wrong? Assigning is problematic?
With 5 and 6 output-> 1.39256
With 7 output-> 1.3925623893
Okey I'm asking a simple question. How can i just output 7 significant digits of this number 1.3925623893 ?
Solution
From gfortran's documentation:
SELECTED_REAL_KIND(P,R) returns the kind value of a real data type with decimal precision of at least P digits
The at least is important. Floating point numbers are most of the time stored using 4 bytes (single precision) or 8 bytes (double precision) and that's it. That's going from asking 6 to 7 significant figures actually adds even more figures: you switched from single to double precision.
What you really want is have a real large enough to store the precision you want, and you already did that correctly, then display only 7 significant figures using a format like:
write(*,'(F12.7)') K