ML Foundations

Avoid intermediate overflow in a two-component magnitude

Compare direct squaring with NumPy hypot for large finite components.

Example results for Avoid intermediate overflow in a two-component magnitude. direct finite: False
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Intermediate values have their own range

For two components, a magnitude can be written as the square root of the sum of their squares. With large floating-point inputs, squaring a component can overflow even when the final mathematical magnitude fits in the floating-point type. Finite types have a maximum representable value. [2]

NumPy hypot calculates the hypotenuse from two legs and is a useful operation to test for this two-component case. Check the actual output and the range of the selected dtype for the data at hand. [1, 2]

References: [1], [2]

Compare the two calculations

Run python examples/numpy_hypot_overflow.py. Each float64 component is 1e200. Their direct squares exceed the finite float64 range, so the direct calculation becomes infinite. The example suppresses the expected overflow warning around that calculation only. [2]

For the same fixture, NumPy hypot returns a finite result. Dividing it by either equal component gives approximately the square root of two. Assertions verify both observations and the expected ratio. [1]

Executed with local Python and NumPy; stdout and checksum are stored in private evidence.

import numpy as np

x = np.float64(1e200)
y = np.float64(1e200)
with np.errstate(over="ignore"):
    direct = np.sqrt(x * x + y * y)
stable = np.hypot(x, y)
assert np.isinf(direct)
assert np.isfinite(stable)
assert np.isclose(stable / x, np.sqrt(2.0))
print("direct finite:", bool(np.isfinite(direct)))
print("hypot finite:", bool(np.isfinite(stable)))
print("hypot / component:", round(float(stable / x), 6))

Recorded output

direct finite: False
hypot finite: True
hypot / component: 1.414214

References: [1], [2]

Check assumptions before using the result

A finite two-component result does not guarantee that arbitrary magnitudes fit the dtype. Inspect nonfinite inputs and output according to the application, and use finfo to inspect the limits of the chosen floating type. [2]

This fixture uses two positive float64 scalars. It demonstrates an intermediate overflow, not an accuracy benchmark or a general method for every multidimensional norm. [1, 2]

References: [1], [2]

Sources

  1. NumPy hypot
  2. NumPy floating-point limits