Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Arrays and Numerics

Numeric Intrinsics and Floating-Point Behavior

Use Fortran's math intrinsics sqrt, exp, log, sin, atan2, hypot, mod, nint and complex functions, and understand rounding, NaN, Infinity, epsilon and ieee_arithmetic.

Numerical work needs a good toolbox of math functions and a clear understanding of how floating-point arithmetic goes wrong. Fortran provides the functions as intrinsics (no import needed) and works on both scalars and whole arrays. This lesson lists them, introduces complex arithmetic and shows where rounding, overflow and NaN come from, so your results stay trustworthy.

Common math intrinsics

All of these are elemental: pass an array and you get an array.

Function Meaning
abs(x) absolute value (also the modulus of a complex)
sqrt(x) square root
exp(x), log(x), log10(x) e to the x, natural log, base-10 log
sin, cos, tan trigonometry, angles in radians
asin, acos, atan inverse trigonometry
atan2(y, x) angle of the point (x, y), in the correct quadrant
sinh, cosh, tanh hyperbolic functions
hypot(x, y) sqrt(x2 + y2) without overflow (2008)
gamma(x), log_gamma(x) the gamma function (2008)
erf(x), erfc(x) error function and its complement (2008)
bessel_j0(x), bessel_y1(x) Bessel functions (2008)

Fortran has no built-in pi. Define it once, accurately, with acos(-1.0_dp):

FORTRAN
program math_demo
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none
  real(dp), parameter :: pi = acos(-1.0_dp)
  real(dp) :: angle

  angle = pi / 6.0_dp
  print *, sin(angle)            ! 0.5 (to rounding)
  print *, atan2(1.0_dp, 1.0_dp) * 4.0_dp   ! pi again
  print *, exp(1.0_dp)           ! e
  print *, log(exp(2.0_dp))      ! 2
end program math_demo

The printed digits are accurate to double precision, but the last one or two may differ by compiler. atan2(y, x) is better than atan(y / x) because it handles x = 0 and knows which quadrant the point is in.

Python Stand-in (Python): math intrinsics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rounding and conversion functions

Function 2.7 -2.7 2.5 Meaning
int(x) 2 -2 2 truncate toward zero
nint(x) 3 -3 3 nearest integer, halves away from zero
floor(x) 2 -3 2 largest integer not above x
ceiling(x) 3 -2 3 smallest integer not below x
anint(x) 3.0 -3.0 3.0 like nint but stays real

Others: mod(a, p) and modulo(a, p) for remainders (see operators), sign(a, b) (magnitude of a, sign of b), max(a, b, ...), min(a, b, ...), and dim(x, y) (positive difference max(x - y, 0)). real(i, dp) and int(x, i8) convert with a chosen kind.

Rounding to a given number of decimals: scale, round, unscale: anint(x * 100.0_dp) / 100.0_dp.

Python Stand-in (Python): int, nint, floor, ceiling table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Complex numbers

A complex holds a real and an imaginary part. The operators work as in mathematics:

FORTRAN
program complex_demo
  implicit none
  complex :: z, w

  z = (3.0, 4.0)               ! 3 + 4i
  w = cmplx(1.0, -2.0)         ! 1 - 2i
  print *, z * w               ! 11 - 2i, worked out below
  print *, abs(z)              ! 5.0, the modulus
  print *, real(z), aimag(z)   ! 3.0 and 4.0
  print *, conjg(z)            ! 3 - 4i
  print *, sqrt(cmplx(-1.0, 0.0))   ! (0.0, 1.0)
end program complex_demo

Multiplying out: (3 + 4i)(1 - 2i) = 3 - 6i + 4i - 8iยฒ = 3 - 2i + 8 = 11 - 2i. Use real(z), aimag(z), conjg(z) and abs(z) for the parts, and exp, sqrt, log also accept complex arguments. Complex numbers support Fourier transforms, AC circuits and quantum mechanics.

Python Stand-in (Python): complex arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How floating-point numbers go wrong

Real numbers are stored in binary with limited digits (see kinds and precision). Four effects matter:

  1. Representation error: 0.1 has no exact binary form, so 0.1 + 0.2 is not exactly 0.3.
  2. Cancellation: subtracting nearly equal numbers wipes out the leading digits. (1.0 + 1e-8) - 1.0 in single precision gives 0.0 or garbage.
  3. Absorption: adding a tiny number to a huge one changes nothing: 1.0e8 + 1.0 in single precision is 1.0e8.
  4. Order of operations: (a + b) + c can differ from a + (b + c). Summing a long array of small numbers onto a large running total loses digits; sum from smallest to largest, or use a higher-precision accumulator.

The remedy is almost always use double precision, compare with a tolerance, and prefer numerically stable formulas (for example, solve a quadratic with the stable form that avoids subtracting close numbers).

Python Stand-in (Python): cancellation and absorption in single precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Infinity, NaN and the ieee_arithmetic module

Floating-point hardware follows the IEEE 754 standard, with special values: Infinity (from overflow or division of a nonzero by zero) and NaN, "not a number" (from 0/0 or sqrt(-1.0) for reals). A NaN is not equal to anything, not even itself. Test for it with a function, never with ==:

FORTRAN
use, intrinsic :: ieee_arithmetic
real :: x

x = ieee_value(x, ieee_quiet_nan)
if (ieee_is_nan(x)) print *, "x is NaN"
print *, ieee_is_finite(1.0 / 3.0)      ! T

By default most compilers let such values flow through the calculation silently, which can hide a mistake until the output is garbage. Compile with -ffpe-trap=invalid,zero,overflow (gfortran) while debugging to stop at the first bad operation; add -g -fbacktrace for a stack trace.

An integer division by zero is different: it typically crashes with a run-time error. The huge, tiny and epsilon intrinsics (see the kinds lesson) report the limits of each kind.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function should you use to find the angle of the point (x, y) in the correct quadrant?

    atan2 handles x = 0 and returns the angle in the right quadrant.
  2. 2. What are nint(-2.5) and int(-2.5)?

    nint rounds halves away from zero giving -3; int truncates toward zero giving -2.
  3. 3. How do you test whether x is NaN?

    Use ieee_is_nan from ieee_arithmetic; a NaN compares unequal to everything, even itself, so == is useless.
  4. 4. Why does (1.0 + 1e-8) - 1.0 often give 0 in single precision?

    Single precision has about 7 digits, so adding 1e-8 to 1.0 is lost entirely.

Summary

  • Math intrinsics (sqrt, exp, log, sin, atan2, hypot, gamma, erf ...) are elemental and need no import; define pi as acos(-1.0_dp).
  • int, nint, floor, ceiling, anint round in different ways; know which one you want.
  • complex is built in, with real, aimag, conjg and abs.
  • Floating-point effects: representation error, cancellation, absorption and order dependence; use double precision and tolerances.
  • Detect NaN and Infinity with ieee_arithmetic, and trap them with compiler flags while debugging.

Next: Subroutines and Functions in Fortran