What Is the Matrix Exponential?

The exponential of a square matrix A is defined by the power series (introduced by Laguerre in 1867)

\mathrm{e}^A = I + A + \displaystyle\frac{A^2}{2!} +                \frac{A^3}{3!} + \cdots.

That the series converges follows from the convergence of the series for scalars. Various other formulas are available, such as

\mathrm{e}^A = \displaystyle\lim_{s\to \infty} (I+A/s)^s.

The matrix exponential is always nonsingular and (\mathrm{e}^A)^{-1} = \mathrm{e}^{-A}.

Much interest lies in the connection between \mathrm{e}^{A+B} and \mathrm{e}^A  \mathrm{e}^B. It is easy to show that \mathrm{e}^{A+B} = \mathrm{e}^A \mathrm{e}^B if A and B commute, but commutativity is not necessary for the equality to hold. Series expansions are available that relate \mathrm{e}^{A+B} to \mathrm{e}^A \mathrm{e}^B for general A and B, including the Baker–Campbell–Hausdorff formula and the Zassenhaus formula, both of which involve the commutator [A,B] = AB - BA. For Hermitian A and B the inequality \mathrm{trace}(\mathrm{e}^{A+B}) \le \mathrm{trace}(\mathrm{e}^A \mathrm{e}^B) was proved independently by Golden and Thompson in 1965.

Especially important is the relation

\mathrm{e}^A = \bigl(\mathrm{e}^{A/2^s}\bigr)^{2^s},

for integer s, which is used in the scaling and squaring method for computing the matrix exponential.

Another important property of the matrix exponential is that it maps skew-symmetric matrices to orthogonal ones. Indeed if A = - A^T then

\bigl(\mathrm{e}^A\bigr)^{-1}    = \mathrm{e}^{-A}    = \mathrm{e}^{A^T}    = \bigl(\mathrm{e}^A\bigr)^T.

This is a special case of the fact that the exponential maps elements of a Lie algebra into the corresponding Lie group.

The matrix exponential plays a fundamental role in linear ordinary differential equations (ODEs). The vector ODE

\displaystyle\frac{dy}{dt} = A y, \quad y(0) = c

has solution y(t) = \mathrm{e}^{At} c, while the solution of the ODE in n \times n matrices

\displaystyle\frac{dY}{dt} = AY + YB, \quad Y(0) = C

is Y(t) = \mathrm{e}^{At}Ce^{Bt}.

In control theory, the matrix exponential is used in converting from continuous time dynamical systems to discrete time ones. Another application of the matrix exponential is in centrality measures for nodes in networks.

Many methods have been proposed for computing the matrix exponential. See the references for details.

References

This is a minimal set of references, which contain further useful references within.

Related Blog Posts

This article is part of the “What Is” series, available from https://nhigham.com/category/what-is and in PDF form from the GitHub repository https://github.com/higham/what-is.

Posted in what-is | Tagged | Leave a comment

Simulating Low Precision Floating-Point Arithmetics in MATLAB

At least five floating-point arithmetics are available in mainstream hardware:

  • the IEEE double precision (fp64), single precision (fp32), and half precision (fp16) formats,
  • bfloat16, and
  • tf32, introduced in the recently announced NVIDIA A100, which uses the NVIDIA Ampere GPU architecture.

Only fp32 and fp64 are available on current Intel processors and most programming environments support only these two precisions. For many of us it is therefore necessary to simulate other precisions if we wish to explore their properties and the behavior of algorithms when run at these precisions.

chop-ex.jpg

Srikara Pranesh and I have written a MATLAB function chop that allows arithmetic of arbitrary precision and exponent range (both lower than fp64) to be simulated. The idea is very simple: variables are stored in fp32 or fp64 and then rounded to the required precision and exponent range after each operation by calling chop. The precision and range, as well as various other parameters, can be changed at any point in the computation.

Our approach can be compared with defining a new data type and storage format and converting to and from single precision or double precision in order to carry out the computations. Our approach avoids the overheads of repeatedly converting to and from the special storage format. It gains speed and generality at the cost of requiring chop calls to be inserted in the code.

Chop is available from this GitHub repository and from MathWorks File Exchange. The motivation behind chop is described in this open access paper in SIAM. J. Sci. Comput. We have made use of chop to simulate fp16 and bfloat16 in several recent papers, including on mixed precision algorithms, probabilistic rounding error analysis, and fast and accurate summation.

How to Use Chop

A call to chop has the form chop(X,options), where the structure options spceifies how to round the elements of the real array X to a lower precision arithmetic. X should be a single precision or double precision array and the output will have the same type. The structure options controls various aspects of the rounding, as we now explain.

  1. The arithmetic format is specified by options.format, which is one of
    • ‘b’, ‘bfloat16’: bfloat16,
    • ‘h’, ‘half’, ‘fp16’: IEEE half precision (the default),
    • ‘s’, ‘single’, ‘fp32’: IEEE single precision,
    • ‘d’, ‘double’, ‘fp64’: IEEE double precision,
    • ‘c’, ‘custom’: custom format.

    In the last case the (base 2) format is defined by options.params, which is a 2-vector [t,emax], where t is the number of bits in the significand (including the hidden bit) and emax is the maximum value of the exponent.

  2. options.subnormal specifies whether subnormal numbers are supported (if they are not, subnormals are flushed to zero):
    • 0 = do not support subnormals (the default for bfloat16),
    • 1 = support subnormals (the default for fp16, fp32, and fp64).
  3. The form of rounding is specified by options.round:
    • 1: round to nearest using round to even last bit to break ties (the default);
    • 2: round towards plus infinity (round up);
    • 3: round towards minus infinity (round down);
    • 4: round towards zero;
    • 5: stochastic rounding—round to the next larger or next smaller floating-point number with probability proportional to 1 minus the distance to those floating-point numbers;
    • 6: stochastic rounding—round to the next larger or next smaller floating-point number with equal probability.

    For stochastic rounding, exact floating-point numbers are not changed.

  4. If options.flip = 1 (default 0) then each element of the rounded result has, with probability options.p (default 0.5), a randomly chosen bit in its significand flipped. This option is useful for simulating soft errors.
  5. If options.explim = 0 (default 1) then emax (the maximal exponent) for the specified arithmetic is ignored, so overflow, underflow, or subnormal numbers will be produced only if necessary for the data type of X. This option is useful for exploring low precisions independent of range limitations.

To avoid repeatedly passing the options argument, one can issue a call chop([],options) and the subsequent calls will use the previously given options parameters. The value of options can be inspected with [~,options] = chop.

In the rest of this post we give examples of the use of chop.

Fp16 versus Bfloat

The code

x = 1/3;
opt_h.format = 'h'; xh = chop(x,opt_h); err_h = (x - xh)/x
opt_b.format = 'b'; xb = chop(x,opt_b); err_b = (x - xb)/x
x = 70000;
xh = chop(x,opt_h)
xb = chop(x,opt_b)

produces the output

err_h =
2.4414e-04
err_b =
-1.9531e-03
xh =
Inf
xb =
70144

which illustrates the higher precison but smaller range of fp16 compared with bfloat16.

Rounding Modes

The code

opt.format = 'h'; x = 0.1; rng(2)
for k = 1:6
opt.round = k;
y(k) = chop(x,opt);
end
errors = y - x
diff_y = diff(y)

rounds 0.1 to fp16 using six different rounding modes. The output is

errors =
-2.4414e-05   3.6621e-05  -2.4414e-05  -2.4414e-05  -2.4414e-05
3.6621e-05
diff_y =
6.1035e-05  -6.1035e-05            0            0   6.1035e-05

Rounding maps a number to the next larger or next smaller floating-point number, so there are only two possibilties for the error, and they have opposite signs. The diff_y values are consistent with the spacing of the fp16 floating-point numbers around 0.1, which is 2^{-11}/8.

Matrix Multiplication

The overheads of chop can be minimized by choosing a suitable implementation of a computation. Matrix multiplication provides a good example. The multiplication C = A*B of n-by-n matrices involves 2n^3 floating-point operations, each of which needs to be chopped. The following code uses only 2n calls to chop, because it processes an outer product in a single call, taking advantage of the fact that chop can take a matrix argument.

A = rand(m,n); B = rand(n,p);
C = zeros(m,p);
for i = 1:n
C = chop(C + chop(A(:,i)*B(i,:)));
end

Tf32 Arithmetic

The recently announced NVIDIA A100 GPU supports a new floating-point format called tf32 in its tensor cores. Tf32 is a 19-bit format that has 11 bits in the significand (including the hidden bit) and 8 bits in the exponent. So it has the precision of fp16 and the range of bfloat16, effectively combining the best features of these two formats. We can simulate tf32 using the custom format of chop. The code

opt.format = 'custom';
% tf32. Significand: 10 bits plus 1 hidden, exponent: 8 bits.
t = 11; emax = 127;
opt.params = [t,emax];
x = 1/3;
xt = chop(x,opt); err_t = (x - xt)/x
x = 70000;
xt = chop(x,opt)

produces the output

err_t =
2.4414e-04
xt =
70016

The error is the same as for fp16 but the number 70000 now rounds to a finite floating-point number.

Posted in software | Tagged | Leave a comment

What Is a Matrix Square Root?

A square root of an n\times n matrix A is any matrix X such that X^2 = A.

For a scalar a (n = 1), there are two square roots (which are equal if a = 0), and they are real if and only if a is real and nonnegative. For n \ge 2, depending on the matrix there can be no square roots, finitely many, or infinitely many. The matrix

A = \begin{bmatrix}      0  &  1 \\      0  &  0      \end{bmatrix}

is easily seen to have no square roots. The matrix

D =  \mathrm{diag}(1,2) =  \begin{bmatrix}                                1  &  0 \\                                0  &  2                               \end{bmatrix}

has four square roots, \mathrm{diag}(\pm 1, \pm\sqrt{2}). The identity matrix

\begin{bmatrix}      1  &  0 \\      0  &  1      \end{bmatrix}

has infinitely many square roots (namely the 2\times 2 involutory matrices), including \mathrm{diag}(\pm 1, \pm 1), the lower triangular matrix

\begin{bmatrix}      1  &  0 \\      1  &  -1      \end{bmatrix},

and any symmetric orthogonal matrix, such as

\begin{bmatrix}      \cos \theta  &  \sin \theta \\      \sin \theta  & -\cos \theta      \end{bmatrix}, \quad \theta \in[0,2\pi]

(which is a Householder matrix). Clearly, a square root of a diagonal matrix need not be diagonal.

The matrix square root of most practical interest is the one whose eigenvalues lie in the right half-plane, which is called the principal square root, written A^{1/2}. If A is nonsingular and has no eigenvalues on the negative real axis then A has a unique principal square root. For the diagonal matrix D above, D^{1/2} = \mathrm{diag}(1,\sqrt{2}).

A symmetric positive definite matrix has a unique symmetric positive definite square root. Indeed if A is symmetric positive definite then it has a spectral decomposition A = QDQ^T, where Q is orthogonal and D is diagonal with positive diagonal elements, and then A^{1/2} = Q D^{1/2}Q^T is also symmetric positive definite.

If A is nonsingular then it has at least 2^s square roots, where s is the number of distinct eigenvalues. The existence of a square root of a singular matrix depends on the Jordan structure of the zero eigenvalues.

In some contexts involving symmetric positive definite matrices A, such as Kalman filtering, a matrix Y such that A = Y^TY is called a square root, but this is not the standard meaning.

When A has structure one can ask whether a square root having the same structure, or some other related structure, exists. Results are known for (for example)

  • stochastic matrices,
  • M-matrices,
  • skew-Hamiltonian matrices,
  • centrosymmetric matrices, and
  • matrices from an automorphism group.

An important distinction is between square roots of A that can be expressed as a polynomial in A (primary square roots) and those that cannot. Square roots of the latter type arise when A has repeated eigenvalues and two copies of an eigenvalue are mapped to different square roots. In some contexts, a nonprimary square root may be the natural choice. For example, consider the matrix

G(\theta) = \begin{bmatrix}      \cos \theta  &  \sin \theta \\      -\sin \theta  & \cos \theta      \end{bmatrix}, \quad \theta \in[0,2\pi],

which represents a rotation through an angle \theta radians clockwise. The natural square root of G(\theta) is G(\theta/2). For \theta = \pi, this gives the square root

G(\pi/2) = \begin{bmatrix}       0 &  1 \\      -1 &  0      \end{bmatrix}

of

G(\pi) = \begin{bmatrix}       -1 & 0 \\        0 & -1      \end{bmatrix}.

The matrix square root arises in many applications, often in connection with other matrix problems such as the polar decomposition, matrix geometric means, Markov chains (roots of transition matrices), quadratic matrix equations, and generalized eigenvalue problems. Most often the matrix is symmetric positive definite, but square roots of nonsymmetric matrices are also needed. Among modern applications, the matrix square root can be found in recent papers on machine learning.

References

This is a minimal set of references, which contain further useful references within.

Related Blog Posts

This article is part of the “What Is” series, available from https://nhigham.com/category/what-is and in PDF form from the GitHub repository https://github.com/higham/what-is.

Posted in what-is | Tagged | Leave a comment

1984 Symposium in Honour of James Wilkinson

In September 1984 a two-day Symposium on Computational Mathematics–State of the Art was held at Argonne National Laboratory in honour of James Hardy Wilkinson on his 65th birthday.

Wilkinson was one of the leading figures in 20th century numerical analysis. He developed the theory and practice of backward error analysis for floating-point computation, and developed, analyzed, and implemented in software many algorithms in numerical linear algebra. Among his many honours, Wilkinson was a Fellow of the Royal Society (elected 1969) and a winner of both the Turing Prize (1970) and the SIAM John von Neumman Lecture award (1970). His legacy endures and in 2019 we celebrated the centenary of his birth with the conference Advances in Numerical Linear Algebra.

The 1984 symposium provided “an overview of the state of the art in several of the major areas of computational mathematics” and “was particularly appropriate for this occasion in view of the many fundamental contributions in computational mathematics made by Professor Wilkinson throughout his distinguished career”.

The symposium attracted more than 260 attendees and comprised ten invited talks by distinguished researchers:

  • Some Problems in the Scaling of Matrices, G. W. Stewart
  • Matrix Calculations in Optimization Algorithms, M. J. D. Powell
  • Numerical Solution of Differential-Algebraic Equations, C. W. Gear
  • The Requirements of Interactive Data Analysis Systems, Peter J. Huber
  • Linear Algebra Problems in Multivariate Approximation Theory, C. de Boor
  • Computational linear Algebra in Continuation and Two Point Boundary Value Problems, H. B. Keller
  • Second Thoughts on the Mathematical Software Effort: A Perspective, W. J. Cody
  • Enhanced Resolution in Shock Wave Calculations, James Glimm
  • Givens’ Eigenvector Recurrence Revisited, Beresford Parlett
  • The State of the Art in Error Analysis, James H. Wilkinson

Slides from the talks are available in an informal proceedings available here in PDF form and on Google Books.

Jack Dongarra has provided me with contact prints of photos taken at the workshop. I have scanned some of these and they are shown below.

One of the photos shows Jim Wilkinson with an Apple Mac that was presented to him. He used it to type up several of his later papers. Sadly, Jim died just over two years after the symposium.

Posted in conferences | Tagged | 2 Comments

Singular Values of Rank-1 Perturbations of an Orthogonal Matrix

What effect does a rank-1 perturbation of norm 1 to an n\times n orthogonal matrix have on the extremal singular values of the matrix? Here, and throughout this post, the norm is the 2-norm. The largest singular value of the perturbed matrix is bounded by 2, as can be seen by taking norms, so let us concentrate on the smallest singular value.

Consider first a perturbation of the identity matrix: B = I + xy^T, for unit norm x and y. The matrix B has eigenvalues 1 (repeated n-1 times) and 1 + y^Tx. The matrix is singular—and hence has a zero singular value—precisely when y^Tx = -1, which is the smallest value that the inner product y^Tx can take.

Another example is B = A + yy^T, where A = I - 2yy^T and y has unit norm, so that A is a Householder matrix. Here, B = I - yy^T is singular with null vector y, so it has a zero singular value,

Let’s take a random orthogonal matrix and perturb it with a random rank-1 matrix of unit norm. We use the following MATLAB code.

n = 100; rng(1)
A = gallery('qmult',n); % Random Haar distrib. orthogonal matrix.
x = randn(n,1); y = randn(n,1);
x = x/norm(x); y = y/norm(y);
B = A + x*y';
svd_B = svd(B);
max_svd_B = max(svd_B), min_svd_B = min(svd_B)

The output is

max_svd_B =
1.6065e+00
min_svd_B =
6.0649e-01

We started with a matrix having singular values all equal to 1 and now have a matrix with largest singular value a little larger than 1 and smallest singular value a little smaller than 1. If we keep running this code the extremal singular values of B do not change much; for example, the next run gives

max_svd_B =
1.5921e+00
min_svd_B =
5.9213e-01

A rank-1 perturbation of unit norm could make A singular, as we saw above, but our random perturbations are producing a well conditioned matrix.

What is the explanation? First, note that a rank-1 perturbation to an orthogonal matrix A can only change two of the singular values, because the singular values are the square roots of the eigenvalues of A^T A, which is the identity plus a rank-2 matrix. So n-2 singular values remain at 1.

A result of Benaych-Georges and Nadakuditi (2012) says that for large n the largest and smallest singular values of B tend to (1+\sqrt{5})/2 = 1.618\dots and (-1+\sqrt{5})/2 = 0.618\dots respectively! As our example shows, n does not have to be large for these limits to be approximations correct to roughly the first digit.

The result in question requires the original orthogonal matrix to be from the Haar distribution, and such matrices can be generated by A = gallery('qmult',n) or by the construction

[Q,R] = qr(randn(n));
Q = Q*diag(sign(diag(R)));

(See What Is a Random Orthogonal Matrix?.) The result also requires u and v to be unit-norm random vectors with independent entries from the same distribution.

However, as the next example shows, the perturbed singular values can be close to the values that the Benaych-Georges and Nadakuditi result predicts even when the conditions of the result are violated:

n = 100; rng(1)
A = gallery('orthog',n);   % Random orthogonal matrix (not Haar).
x = rand(n,1); y = (1:n)'; % Non-random y.
x = x/norm(x); y = y/norm(y);
B = A + x*y';
svd_B = svd(B);
max_svd_B = max(svd_B), min_svd_B = min(svd_B)
max_svd_B =
1.6069e+00
min_svd_B =
6.0687e-01

The question of the conditioning of a rank-1 perturbation of an orthogonal matrix arises in the recent EPrint Random Matrices Generating Large Growth in LU Factorization with Pivoting.

Posted in research | Tagged , | Leave a comment

Which Fountain Pen Ink for Writing Mathematics?

If, like me, you sometimes prefer to write mathematics on paper before typing into LaTeX, you have the choice of pencil or pen as your writing tool. I’ve written before about writing in pencil. My current tools of choice are fountain pens.

A fountain pen, the ink it contains and the paper used are three independent variables that combine in a complicated way to affect the experience of writing and the results produced. Here, I focus solely on inks and ask what ink one should choose depending on different mathematics-focused requirements.

I give links to reviews on the excellent Mountain of Ink and Pen Addict websites and other pen/ink websites. Unless otherwise stated, I have tried the inks myself.

191224_inks-1.jpg

Fast Drying Time

When we write down mathematical working, perhaps in the course of doing research, we are likely to need to go back and make changes to what we have just written. A fast drying ink helps avoid smudges, and it also means we can start writing on the reverse side of a page without pausing to let the ink dry or using blotting paper. Left-handed writers may always need such an ink, depending on their particular style of writing. My favourite fast-drying ink is Noodler’s Bernanke Blue, which is named after Ben Bernanke, former chairman of the Federal Reserve. Downsides are feathering (where the ink spreads out to create rough edges) and bleeding (where ink soaks through on the other side of the page) on lesser grades of paper.

Water Resistance

As mathematicians are major consumers of coffee, what we write risks being spilled on. (Indeed this is so normal an occurrence that Hanno Rein has written a LaTeX package to simulate a coffee stain.) An ink should be reasonably water resistant if spills are not to blur what we have written. Many popular inks have poor water resistance. One of the most water resistant is Noodler’s Bulletproof Black, which also “resists all the known tools of a forger, UV light, UV light wands, bleaches, alcohols, solvent…”. It’s great for writing cheques, as well as mathematics. (But it may not be the blackest black ink, if that matters to you.) Another water resistant ink is Noodler’s Baystate Blue (see below).

Interesting Names

Sometimes, writing with an interestingly named pen, paper or ink can provide inspiration. While many Coloverse inks have a space or physics theme, I am not aware of any mathematically named inks.

Vibrant Inks

Vibrant inks are great for annotating a printout or writing on paper with heavy lines, squares or dots. An outstanding ink in this respect is Noodler’s Baystate Blue, an incredibly intense, bright blue that jumps off the page. The downsides are bleeding and staining. An ink to be used with caution! I also like the much better behaved Pilot Iroshizuku Fuyu-gaki (orange) and Pilot Iroshizuku Kon-peki (blue).

191224_inks-2.jpg

For Marking (Grading)

For marking scripts one obviously needs to use a different colour than the student has used. Traditionally, this is red. A couple of my favourites for marking are Waterman Audacious Red and Cult Pens Deep Dark Orange.

Shading, Sheen and Shimmer

Many inks have one or more of the properties of shading, sheen and shimmer. Shading is where an ink appears darker or lighter in different parts of a stroke; sheen is where an ink shines with a different colour; and shimmer is where particles have been added to the ink that cause it to shimmer or glisten when it catches the light. The strength of all these effects is strongly dependent on the pen, the nib size and the paper, and for shimmer the pen needs to be moved around to distribute the particles before writing. (Sheen and shimmer do not show up well on the scans shown in this post.) Among my favourites are Diamine Majestic Blue (blue with purple sheen), Robert Oster Fire and Ice (teal with shading and pink sheen) and Diamine Cocoa Shimmer (brown with gold shimmer). For “monster sheen”, try Organic Studios Nitrogen Royal Blue, but note that it is hard to clean out of a pen.

191224_inks-3.jpg

Nonstandard Surfaces

Much mathematics is written on bar mats, napkins, paper towels, backs of envelopes, newspapers, tablecloths, and anything that is to hand, especially when mathematicians work together away from their desks. These surfaces are not fountain-pen friendly. One promising ink for such situations is Noodler’s X-Feather, which was created to combat feathering on cheap paper. (I have not tried this ink.)

All Rounders

Finally, three good all-round inks that I’ve used a lot when working on my books and papers are Diamine Asa Blue, Diamine Oxford Blue, and Diamine Red Dragon.

191224_inks-4.jpg

Posted in writing | Leave a comment

What Is IEEE Standard Arithmetic?

The IEEE Standard 754, published in 1985 and revised in 2008 and 2019, is a standard for binary and decimal floating-point arithmetic. The standard for decimal arithmetic (IEEE Standard 854) was separate when it was first published in 1987, but it was included with the binary standard from 2008. We focus here on the binary part of the standard.

The standard specifies floating-point number formats, the results of the basic floating-point operations and comparisons, rounding modes, floating-point exceptions and their handling, and conversion between different arithmetic formats.

A binary floating-point number is represented as

y = \pm m \times 2^{e-t},

where t is the precision and e\in [e_{\min},e_{\max}] is the exponent. The significand m is an integer satisfying m \le 2^t-1. Numbers with m \ge 2^{t-1} are called normalized. Subnormal numbers, for which 0 < m <2^{t-1} and e = e_{\min}, are supported.

Four formats are defined, whose key parameters are summarized in the following table. The second column shows the number of bits allocated to store the significand and the exponent. I use the prefix “fp” instead of the prefix “binary” used in the standard. The unit roundoff is u = 2^{-t}.

ieee_params_table.jpg Fp32 (single precision) and fp64 (double precision) were in the 1985 standard; fp16 (half precision) and fp128 (quadruple precision) were introduced in 2008. Fp16 is defined only as a storage format, though it is widely used for computation.

The size of these different number systems varies greatly. The next table shows the number of normalized and subnormal numbers in each system.

flpt_count.jpg

We see that while one can easily carry out a computation on every fp16 number (to check that the square root function is correctly computed, for example), it is impractical to do so for every double precision number.

A key feature of the standard is that it is a closed system, thanks to the inclusion of NaN (Not a Number) and \infty (usually written as inf in programing languages) as floating-point numbers: every arithmetic operation produces a number in the system. A NaN is generated by operations such as

0/0, \quad 0 \times \infty, \quad \infty/\infty, \quad (+\infty) + (-\infty), \quad \sqrt{-1}.

Arithmetic operations involving a NaN return a NaN as the answer. The number \infty obeys the usual mathematical conventions regarding infinity, such as

\infty+\infty = \infty, \quad (-1)\times\infty = -\infty, \quad   ({\textrm{finite}})/\infty = 0.

This means, for example, that 1 + 1/x evaluates as 1 when x = \infty.

The standard specifies that all arithmetic operations (including square root) are to be performed as if they were first calculated to infinite precision and then rounded to the target format. A number is rounded to the next larger or next smaller floating-point number according to one of four rounding modes:

  • round to the nearest floating-point number, with rounding to even (rounding to the number with a zero least significant bit) in the case of a tie;
  • round towards plus infinity and round towards minus infinity (used in interval arithmetic); and
  • round towards zero (truncation, or chopping).

For round to nearest it follows that

\mathrm{f\kern.2ptl}(x\mathbin{\mathrm{op}} y)     = (x \mathbin{\mathrm{op}} y)(1+\delta),     \quad |\delta|\le u, \quad \mathbin{\mathrm{op}}\in\{+,-,*,/,\sqrt{}\},

where \mathrm{f\kern.2ptl} denotes the computed result. The standard also includes a fused multiply-add operation (FMA), x*y + z. The definition requires it to be computed with just one rounding error, so that \mathrm{f\kern.2ptl}(x*y+z) is the rounded version of x*y+z, and hence satisfies

\mathrm{f\kern.2ptl}(x*y + z) = (x*y + z)(1+\delta), \quad |\delta|\le u.

FMAs are supported in some hardware and are usually executed at the same speed as a single addition or multiplication.

The standard recommends the provision of correctly rounded exponentiation (x^y) and transcendental functions (\exp, \log, \sin, \mathrm{acos}, etc.) and defines domains and special values for them, but these functions are not required.

A new feature of the 2019 standard is augmented arithmetic operations, which compute \mathrm{fl}(x \mathbin{\mathrm{op}}y) along with the error x\mathbin{\mathrm{op}}y - \mathrm{fl}(x \mathbin{\mathrm{op}}y), for \mathbin{\mathrm{op}} = +,-,*. These operations are useful for implementing compensated summation and other special high accuracy algorithms.

William (“Velvel”) Kahan of the University of California at Berkeley received the 1989 ACM Turing Award for his contributions to computer architecture and numerical analysis, and in particular for his work on IEEE floating-point arithmetic standards 754 and 854.

References

This is a minimal set of references, which contain further useful references within.

Posted in what-is | Tagged | Leave a comment

What Is Floating-Point Arithmetic?

A floating-point number system F is a finite subset of the real line comprising numbers of the form

y = \pm m \times \beta^{e-t},

where \beta is the base, t is the precision, and e\in [e_{\min},e_{\max}] is the exponent. The system is completely defined by the four integers \beta, t, e_{\min}, and e_{\max}. The significand m satisfies 0 \le m \le \beta^t-1. Normalized numbers are those for which m \ge \beta^{t-1}, and they have a unique representation. Subnormal numbers are those with 0 < m < \beta^{t-1} and e = e_{\min}.

An alternative representation of y\in F is

y = \pm \beta^e               \left( \displaystyle\frac{d_1}{\beta} +                      \frac{d_2}{\beta^2} + \cdots +                      \frac{d_t}{\beta^t} \right)         = \pm \beta^e \times .d_1 d_2 \dots d_t,

where each digit d_i satisfies 0 \le d_i \le \beta-1 and d_1 \ne 0 for normalized numbers.

The floating-point numbers are not equally spaced, but they have roughly constant relative spacing (varying by up to a factor \beta).

Here are the normalized nonnegative numbers in a toy system with \beta = 2, t = 3, and e \in [-1, 3].

flpt_numbers_fig.jpg

Three key properties that hold in general for binary arithmetic are visible in this example.

  • The spacing of the numbers increases by a factor 2 at every power of 2.
  • The spacing of the numbers between 1/2 and 1 is u = 2^{-t}, which is called the unit roundoff. The spacing of the numbers between 1 and 2 is \epsilon = 2^{1-t}, which is called the machine epsilon. Note that \epsilon = 2u.
  • There is a gap between 0 and the smallest normalized number, which is 2^{e_{\min}-1}. The subnormal numbers fill this gap with numbers having the same spacing as those between 2^{e_{\min}-1} and 2^{e_{\min}}, namely 2^{e_{\min}-t}. The next diagram shows the complete set of nonnegative normalized and subnormal numbers in the toy system.

flpt_numbers_all_fig.jpg

In MATLAB, eps is the machine epsilon, eps(x) is the distance from x to the next larger (in magnitude) floating-point number, realmax is the largest finite number, and realmin is the smallest normalized positive number.

A real number x is mapped into F by rounding, and the result is denoted by \mathrm{f\kern.2ptl}(x). If x exceeds the largest number in F then we say that \mathrm{f\kern.2ptl}(x) overflows, and in IEEE arithmetic it is represented by Inf. If x\in F then \mathrm{f\kern.2ptl}(x) = x; otherwise, x lies between two floating-point numbers and we need a rule for deciding which one to round x to. The usual rule, known as round to nearest, is to round to whichever number is nearer. If x is midway between two floating-point numbers then we need a tie-breaking rule, which is usually to round to the number with an even last digit. If x\ne0 and \mathrm{f\kern.2ptl}(x) = 0 then \mathrm{f\kern.2ptl}(x) is said to underflow.

For round to nearest it can be shown that

\mathrm{f\kern.2ptl}(x)  = x(1+\delta), \quad |\delta|\le u.

This result shows that rounding introduces a relative error no larger than u.

Elementary floating-point operations, +, -, *, /, and \sqrt{} are usually defined to return the correctly rounded exact result, so they satisfy

\mathrm{f\kern.2ptl}(x\mathbin{\mathrm{op}} y)     = (x \mathbin{\mathrm{op}} y)(1+\delta),     \quad |\delta|\le u, \quad \mathbin{\mathrm{op}}\in\{+,-,*,/,\sqrt{}\}.

Most floating-point arithmetics adhere to the IEEE standard, which defines several floating-point formats and four different rounding modes.

Another form of finite precision arithmetic is fixed-point arithmetic, in which numbers have the same form as F but with a fixed exponent e, so all the numbers are equally spaced. In most scientific computations scale factors must be introduced in order to be able to represent the range of numbers occurring. Fixed-point arithmetic is mainly used on special purpose devices such as FPGAs and in embedded systems.

References

This is a minimal set of references, which contain further useful references within.

Related Blog Posts

This article is part of the “What Is” series, available from https://nhigham.com/category/what-is and in PDF form from the GitHub repository https://github.com/higham/what-is.

Posted in what-is | Leave a comment

What Is Rounding?

Rounding is the transformation of a number expressed in a particular base to a number with fewer digits. For example, in base 10 we might round the number x = 7.146 to 7.15, which can be described as rounding to three significant digits or two decimal places. Rounding does not change a number if it already has the requisite number of digits.

The three main uses of rounding are

  • to simplify a number in base 10 for human consumption,
  • to represent a constant such as 1/3, \pi, or \sqrt{7} in floating-point arithmetic,
  • to convert the result of an elementary operation (an addition, multiplication, or division) on floating-point numbers back into a floating-point number.

The floating-point numbers may be those used on a computer (base 2) or a pocket calculator (base 10).

Rounding can be done in several ways.

Round to Nearest

The most common form of rounding is to round to the nearest number with the specified number of significant digits or decimal places. In the example above, the two nearest numbers to x with three significant digits are 7.14 and 7.15, at distances 0.006 and 0.004, respectively, from x. The nearest of these two numbers, 7.15, is chosen.

What happens if the two candidate numbers are equally close? We need a rule for breaking the tie. The most common choices are

  • round to even: choose the number with an even last digit,
  • round to odd: choose the number with an odd last digit.

If we round 1.85 to two significant digits, the result is 1.8 with round to even and 1.9 with round to odd.

There are several reasons for preferring to break ties with round to even.

  • In bases 2 and 10 a subsequent rounding to one less place does not involve a tie. Thus we have the rounding sequence 2.445, 2.44, 2.4, 2 with round to even, but 2.445, 2.45, 2.5, 3 with round to odd.
  • For base 2, round to even results in integers more often, as a consequence of producing a zero least significant bit.
  • In base 10, after round to even a rounded number can be halved without error.

IEEE Standard 745 for floating-point arithmetic supports three tie-breaking methods: round to even (the default), round to the number with larger magnitude, and round towards zero (introduced in the 2019 revision for use with the standard’s new augmented operations).

The tie-breaking rule taught in UK schools, for decimal arithmetic, is to round up on ties. The rounding rule then becomes: round down if the first digit to be dropped is 4 or less and otherwise round up.

Round Towards Plus or Minus Infinity

Another possibility is to round to the next larger number with the specified number of digits, which is known as round towards plus infinity (or round up). Then 1.85 rounds to 1.9 and -2.34 rounds to -2.3. Similarly, with round towards minus infinity (or round down) we round to the next smaller number, so that 1.85 rounds to 1.8 and -2.34 rounds to -2.4.

This form of rounding is used in interval arithmetic, where an interval guaranteed to contain the exact result is computed in floating-point arithmetic.

Round Towards Zero

In this form of rounding we round towards zero, that is, we round x down if x > 0 and round it up if x < 0. This is also known as chopping, or truncation.

Stochastic Rounding

Stochastic rounding was proposed in the 1950s and is attracting renewed interest, especially in machine learning. It rounds up or down randomly. It come in two forms. The first form rounds up or down with equal probability 1/2. To describe the second form, let x be the given number and let x_1  x be the candidates for the result of rounding. We round up to x_2 with probability (x-x_1)/(x_2-x_1) and down to x_1 with probability (x_2-x)/(x_2-x_1); note that these probabilities sum to 1. In floating-point arithmetic, stochastic rounding overcomes the problem that can arise in summing a set of numbers whereby some individual summands are so small that they do not contribute to the computed sum even though they contribute to the exact sum.

The diagrams below illustrate round to nearest (RN), round towards zero (RZ), round towards plus infinity (\mathrm{R}^{+\infty}), and round towards minus infinity (\mathrm{R}^{-\infty}). They show the number x to be rounded in four different configurations with respect to the origin and the midpoint (drawn with a dotted line) of the interval between the two candidate rounding results (drawn with a solid line). The red arrows point to the two possible results of rounding.

rounding_fig.jpg

Real World Rounding

The European Commission’s rules for converting currencies of Member States into Euros (from the time of the creation of the Euro) specify that “half-way results are rounded up” (rounded to plus infinity). (PDF link)

The International Association of Athletics Federations (IAAF) specifies in Rule 165 of its Competition Rules 2018–2019 that all times of track races up to 10,000m should be recorded to a precision of 0.01 second, with rounding to plus infinity. In 2006, the athlete Justin Gatlin was wrongly credited with breaking the 100m world record when his official time of 9.766 seconds was rounded down to 9.76 seconds. Under the IAAF rules it should have been rounded up to 9.77 seconds, matching the world record set by Asafa Powell the year before. The error was discovered several days after the race.

In meteorology, rounding to nearest with ties broken by rounding to odd is favoured. Hunt suggests that the reason is to avoid falsely indicating that it is freezing. Thus 0.5^\circC and 32.5^\circF round to 1^\circC and 33^\circF instead of 0^\circC and 32^\circF.

Useful Tool

The \LaTeX package siunitx has the ability to round numbers (in base 10) to a specified number of decimal places or significant figures.

References

This is a minimal set of references, which contain further useful references within.

Related Blog Posts

  • What Is Floating-Point Arithmetic? (2020)—forthcoming
  • What Is IEEE Standard Arithmetic? (2020)—forthcoming

This article is part of the “What Is” series, available from https://nhigham.com/category/what-is and in PDF form from the GitHub repository https://github.com/higham/what-is.

Posted in what-is | 1 Comment

What Is a Random Orthogonal Matrix?

Various explicit parametrized formulas are available for constructing orthogonal matrices. To construct a random orthogonal matrix we can take such a formula and assign random values to the parameters. For example, a Householder matrix H = I - 2uu^T/(u^Tu) is orthogonal and symmetric and we can choose the nonzero vector u randomly. Such an example is rather special, though, as it is a rank-1 perturbation of the identity matrix.

What is usually meant by a random orthogonal matrix is a matrix distributed according to the Haar measure over the group of orthogonal matrices. The Haar measure provides a uniform distribution over the orthogonal matrices. Indeed it is invariant under multiplication on the left and the right by orthogonal matrices: if Q is from the Haar distribution then so is UQV for any orthogonal (possibly non-random) U and V. A random Householder matrix is not Haar distributed.

A matrix from the Haar distribution can be generated as the orthogonal factor in the QR factorization of a random matrix with elements from the standard normal distribution (mean 0, variance 1). In MATLAB this is done by the code

[Q,R] = qr(randn(n));
Q = Q*diag(sign(diag(R)));

The statement [Q,R] = qr(randn(n)), which returns the orthogonal factor Q, is not enough on its own to give a Haar distributed matrix, because the QR factorization is not unique. The second line adjusts the signs so that Q is from the unique factorization in which the triangular factor R has nonnegative diagonal elements. This construction requires 2n^3 flops.

A more efficient construction is possible, as suggested by Stewart (1980). Let x_k be an (n-k+1)-vector of elements from the standard normal distribution and let H_k be the Householder matrix that reduces x_k to r_{kk}e_1, where e_1 is the first unit vector. Then Q = DH'_1H'_2\dots H'_{n-1} is Haar distributed, where H'_k = \mathrm{diag}(I_{k-1}, H_k), D = \mathrm{diag}(\mathrm{sign}(r_{kk})), and r_{nn} = x_n. This construction expresses Q as the product of n-1 Householder matrices of growing effective dimension, and the product can be formed from right to left in 4n^3/3 flops. The MATLAB statement Q = gallery('qmult',n) carries out this construction.

A similar construction can be made using Givens rotations (Anderson et al., 1987).

Orthogonal matrices from the Haar distribution can also be formed as Q = A (A^TA)^{-1/2}, where the elements of A are from the standard normal distribution. This Q is the orthogonal factor in the polar decomposition A = QH (where H is symmetric positive semidefinite).

Random orthogonal matrices arise in a variety of applications, including Monte Carlo simulation, random matrix theory, machine learning, and the construction of test matrices with known eigenvalues or singular values.

All these ideas extend to random unitary (complex) matrices. In MATLAB, Haar distributed unitary matrices can be constructed by the code

[Q,R] = qr(complex(randn(n),randn(n)));
Q = Q*diag(sign(diag(R)));

This code exploits the fact that the R factor computed by MATLAB has real diagonal entries. If the diagonal of R were complex then this code would need to be modified to use the complex sign function given by \mathrm{sign}(z) = z/|z|.

References

This is a minimal set of references, which contain further useful references within.

Related Blog Posts

This article is part of the “What Is” series, available from https://nhigham.com/category/what-is and in PDF form from the GitHub repository https://github.com/higham/what-is.

Posted in what-is | Leave a comment