IEEE arithmetic
Use ieee_arithmetic
The intrinsic module ieee_arithmetic gives portable access to IEEE floating point queries. Add a use statement for it at the top of the unit, before implicit none. Start by asking whether the processor supports quiet NaN values.
program ieee_use
use, intrinsic :: ieee_arithmetic
implicit none
real :: x = 1.0
logical :: ok
ok = ieee_support_nan(x)
print *, ok
end program ieee_use
T
Detect NaN
Quiet NaN values poison every computation they touch, so detect them early. Build one portably with ieee_value, then test with ieee_is_nan. Never compare with == because NaN is unequal to everything, including itself.
program nan_demo
use, intrinsic :: ieee_arithmetic
implicit none
real :: x
x = ieee_value(x, ieee_quiet_nan)
if (ieee_is_nan(x)) write(*, "(a)") "got NaN"
end program nan_demo
Handle infinities
Overflow can produce infinities instead of stopping the program. Build positive infinity with ieee_value and test with ieee_is_finite. Branch to safe fallback code when a value is not finite.
program inf_demo
use, intrinsic :: ieee_arithmetic
implicit none
real :: x
x = ieee_value(x, ieee_positive_inf)
if (.not. ieee_is_finite(x)) write(*, "(a)") "infinite"
end program inf_demo
Halt on exceptions
By default most builds continue past exceptions and just record a flag. Read the current halting mode and turn halting on for the exceptions you care about, such as overflow. Do this once at startup so faults surface at once.
program halt_demo
use, intrinsic :: ieee_arithmetic
implicit none
logical :: halting
call ieee_get_halting_mode(ieee_overflow, halting)
call ieee_set_halting_mode(ieee_overflow, .true.)
end program halt_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