Avoiding Intermediate Overflow in a Euclidean Norm

A square-and-sum formula can overflow before taking a square root even when the actual norm fits.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a scaled formula
  2. Handle the exceptional scale
  3. Divide by the maximum before squaring
  4. Check zero and non-finite inputs explicitly

Trace a scaled formula

For \(a,b\), let \(m=\max(|a|,|b|)\). If \(m>0\), compute \(m\sqrt{(a/m)^2+(b/m)^2}\). This keeps the squared ratios at most one. For 3 and 4 the scaling gives five, the same exact result. Fixed representable ranges motivate checking intermediates.

Handle the exceptional scale

When both inputs are zero the norm is zero without division. See guard clauses for an implementation of that boundary.[1][2]

Divide by the maximum before squaring

With binary64 values \(3\cdot10^{200}\) and \(4\cdot10^{200}\), squaring either can overflow although their Euclidean norm \(5\cdot10^{200}\) is finite. Scale by \(m=4\cdot10^{200}\), evaluate the norm of \(0.75,1\), then multiply by \(m\). See Euclidean distance.

Scale m=4e200
Scaled vector (0.75, 1)
Scaled norm 1.25
Final norm 5e200

Check zero and non-finite inputs explicitly

Scaling the zero vector by its largest component would divide by zero. Define how infinities and NaNs are handled or use a thoroughly tested norm routine. Test small magnitudes susceptible to underflow too.

References

  1. Tobin A. Driscoll and Richard J. Braun, Fundamentals of Numerical Computation ↩
  2. Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms ↩