Numeric models

Epsilon spacing

Real numbers have gaps. The epsilon intrinsic returns the distance from 1.0 to the next larger value for a given kind.

Use epsilon to set sensible tolerances instead of comparing reals for exact equality.

program eps_demo implicit none real :: x x = 1.0 print *, epsilon(x) if (abs(x - 1.0) .lt. epsilon(x)) then print *, "close to one" end if end program eps_demo

Huge and tiny

The huge intrinsic returns the largest finite value and tiny returns the smallest positive normal value for a kind.

Check limits before a risky computation to avoid overflow to infinity or underflow to zero.

program limits_demo implicit none real :: x x = 1.0 print *, huge(x) print *, tiny(x) end program limits_demo

Digits and radix

The digits intrinsic counts significant decimal digits and radix reports the number base used by the model, usually two.

Query them when you document accuracy or compare what two different kinds can represent.

program digits_demo implicit none real :: x integer :: d integer :: r x = 1.0 d = digits(x) r = radix(x) print *, "digits =", d, "radix =", r end program digits_demo

Choose kinds deliberately

Pick a kind once with selected_real_kind and name it, then use that name for every real in the unit.

This keeps precision in one place. To change accuracy later you edit one line instead of the whole file.

program kind_demo implicit none integer, parameter :: dp = selected_real_kind(15, 307) real(dp) :: a a = 1.0_dp print *, epsilon(a), huge(a) end program kind_demo

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev