Mathematical Foundations

VIII.4 · Numerical Computing

Where did the meaningful digits go?

Subtract nearby square roots, then evaluate the same mathematical result through rationalization. Inspect actual binary64 intermediates and a live rational enclosure of the true real answer.

Compare subtraction with rationalization

Exact result is 1/(sqrt(x+1)+sqrt(x)); its live rational enclosure is independently checked by Python Decimal. Naive binary64 subtraction ≈ 0; rationalized binary64 answer ≈ 0.000000005. The computed x+1 equals stored x: the increment was rounded away. Error intervals bound computed minus the true real result. Scope: 0 ≤ x ≤ 1e300; this avoids denominator overflow here.

Real reference (rounded enclosure midpoint)
0.000000005
Naive subtraction
0
Rationalized evaluation
0.000000005
Computed sqrt(x+1)
1×10⁸
Computed sqrt(x)
1×10⁸
Increment rounded away?
true

= exact rationals or classifications · ≈ a formatted numerical display. Exceptional values retain their stated meaning.

x+1−x=1x+1+x,x≥0\sqrt{x+1}-\sqrt x=\frac1{\sqrt{x+1}+\sqrt x},\quad x\ge0
Rational enclosures: exact endpoints, not claimed exact decimal answers.
quantitylower boundupper bound
true real result1684996666696914987166688442938726917102321526408785780068975640576/336999333339383005858321022072320108629323182861028876918514248536275852535842498333348457493583344221469363458551160763204392890034487820288/168499666669691502929160511036160054314661591430514438459257124268137926267
naive signed error-842498333348457493583344221469363458551160763204392890034487820288/168499666669691502929160511036160054314661591430514438459257124268137926267-1684996666696914987166688442938726917102321526408785780068975640576/336999333339383005858321022072320108629323182861028876918514248536275852535
stable signed error23386477134095145244355090335041903565634331042626669317560467790414513647/10185179881672430685971725483857645223075626974233250082592777439138271057661995739986784083876249646772954268190290488710180670083807131268662085253338635123957895378063867/203703597633448613719434509677152904461512539484665001651855548782765421153844377709542996264878080

Add then take square roots

These are actual binary64 intermediates, including a possibly lost increment.

Inspect the recorded values\text{Inspect the recorded values}
Actual intermediate values; = exact rationals, ≈ binary64 displays.
quantityvalue
storedX≈ 1×10¹⁶
plusOne≈ 1×10¹⁶
rootA≈ 1×10⁸
rootB≈ 1×10⁸

0 ≤ x ≤ 1e300; scientific notation allowed.

Replay the actual roots and subtraction, then the reciprocal of their sum. Rational intervals bound the true result and both signed errors.

Intuition: a difference smaller than the operands

When two large nearby values are rounded independently, their small difference can depend on digits that storage already discarded. Subtraction removes their shared leading digits and exposes the uncertainty in the remaining ones. The result can be zero even when the mathematical difference is positive.

Start at x=1e16. Both computed square roots coincide, so naive subtraction gives zero. The algebraically equivalent reciprocal of their sum remains positive. Replay the addition before the roots: at this scale, even x+1 can equal stored x in binary64.

Definition: the mathematical result and two algorithms

For x≥0 define

f(x)=x+1−x.f(x)=\sqrt{x+1}-\sqrt x.

Both square roots are real, the first is strictly larger, and f(x)>0 for finite x. The naive algorithm adds one, takes two rounded roots and subtracts them. The rationalized algorithm adds those positive roots, then reciprocates:

f(x)=1x+1+x.f(x)=\frac1{\sqrt{x+1}+\sqrt x}.

These identities concern exact real arithmetic. Their floating-point implementations retain different sequences of rounding. The explorer distinguishes the exact expression, its reference enclosure, each computed answer and each computed-minus-real error interval.

Mechanics: inspect the actual operands

The stage records the intended exact decimal x, its binary64 representation, computed x+1, both square roots, naive subtraction, the stable denominator and its reciprocal. The same records feed every table and replay frame.

The real reference is not the naive result recomputed in a second language. The browser builds rational lower and upper bounds for each exact square root using an integer-square-root construction with 220 fractional binary bits. Reciprocating the bounded positive sum gives a containing interval for the mathematical result. Python independently checks that interval using 450-digit Decimal square roots. The reference display is the rounded midpoint, explicitly an approximation.

Derivation: multiply by the conjugate

Multiply numerator and denominator by the positive conjugate:

x+1−x=(x+1)−xx+1+x=1x+1+x.\sqrt{x+1}-\sqrt x=\frac{(x+1)-x}{\sqrt{x+1}+\sqrt x}=\frac1{\sqrt{x+1}+\sqrt x}.

The exact numerator is one. The stable implementation uses that exact identity instead of forming a difference of rounded roots. It does not recover a lost input increment; it evaluates the mathematical identity by a route that does not require that increment to survive subtraction.

If al≤x+1≤aua_l\le\sqrt{x+1}\le a_u and bl≤x≤bub_l\le\sqrt x\le b_u, positivity reverses the reciprocal bounds:

1au+bu≤f(x)≤1al+bl.\frac1{a_u+b_u}\le f(x)\le\frac1{a_l+b_l}.

For a computed rational q, subtract the upper and lower reference endpoints to get a signed error enclosure. This makes the measurement honest even though f(x) is generally irrational.

Worked example: x = 10000000000000000

The true difference is approximately 5×10−95\times10^{-9}. Its exact value is positive; no finite decimal display is presented as an exact radical answer. Binary64 rounds x+1 back to x at this scale. Both roots then evaluate to 100000000, and the naive subtraction evaluates to zero.

The rationalized denominator evaluates to 200000000. Its reciprocal is approximately 5×10−95\times10^{-9} and has a small, independently checked error interval. The naive error is approximately the negative of the whole real result, corresponding to complete relative loss.

At x=0 the exact result is one; both methods return one. At x=1 the result is 2−1\sqrt2-1, and neither method has a general exact-binary guarantee. Compare the error enclosures rather than inferring exactness from a short display. At x=1e300 the stable result is near 5×10−1515\times10^{-151}; it remains finite in the bounded experiment.

Worked example: Compare subtraction with rationalization

Exact result is 1/(sqrt(x+1)+sqrt(x)); its live rational enclosure is independently checked by Python Decimal. Naive binary64 subtraction ≈ 0; rationalized binary64 answer ≈ 0.000000005. The computed x+1 equals stored x: the increment was rounded away. Error intervals bound computed minus the true real result. Scope: 0 ≤ x ≤ 1e300; this avoids denominator overflow here.

Real reference (rounded enclosure midpoint)
0.000000005
Naive subtraction
0
Rationalized evaluation
0.000000005
Computed sqrt(x+1)
1×10⁸
Computed sqrt(x)
1×10⁸
Increment rounded away?
true

= exact rationals or classifications · ≈ a formatted numerical display. Exceptional values retain their stated meaning.

x+1−x=1x+1+x,x≥0\sqrt{x+1}-\sqrt x=\frac1{\sqrt{x+1}+\sqrt x},\quad x\ge0
Rational enclosures: exact endpoints, not claimed exact decimal answers.
quantitylower boundupper bound
true real result1684996666696914987166688442938726917102321526408785780068975640576/336999333339383005858321022072320108629323182861028876918514248536275852535842498333348457493583344221469363458551160763204392890034487820288/168499666669691502929160511036160054314661591430514438459257124268137926267
naive signed error-842498333348457493583344221469363458551160763204392890034487820288/168499666669691502929160511036160054314661591430514438459257124268137926267-1684996666696914987166688442938726917102321526408785780068975640576/336999333339383005858321022072320108629323182861028876918514248536275852535
stable signed error23386477134095145244355090335041903565634331042626669317560467790414513647/10185179881672430685971725483857645223075626974233250082592777439138271057661995739986784083876249646772954268190290488710180670083807131268662085253338635123957895378063867/203703597633448613719434509677152904461512539484665001651855548782765421153844377709542996264878080

Add then take square roots

These are actual binary64 intermediates, including a possibly lost increment.

Inspect the recorded values\text{Inspect the recorded values}
Actual intermediate values; = exact rationals, ≈ binary64 displays.
quantityvalue
storedX≈ 1×10¹⁶
plusOne≈ 1×10¹⁶
rootA≈ 1×10⁸
rootB≈ 1×10⁸

Select the recorded intermediate values. Previous, next and direct replay navigation preserve immutable numerical history.

Executable reference code

The pedagogical program computes actual binary64 intermediates and a Decimal450 reference through the rationalized mathematical identity. The NumPy version applies both algorithms to arrays and checks the stable answers against independent high-precision values at the actual stored inputs. For an intended-decimal comparison, evaluate the expression at the exact decimal input instead; intended and stored-input references answer different questions.

code/python/catastrophic_cancellation.py
from decimal import Decimal, localcontext
from math import sqrt
if __name__ == '__main__':
    for text in ['0', '1', '1e16', '1e100', '1e300']:
        x = float(text); naive = sqrt(x+1)-sqrt(x); stable = 1/(sqrt(x+1)+sqrt(x))
        with localcontext() as ctx:
            ctx.prec = 450; exact_x = Decimal(text)
            reference = 1/((exact_x+1).sqrt()+exact_x.sqrt())
            print(text, 'naive', naive, 'stable', stable, 'real reference', reference)
            assert abs(Decimal.from_float(stable)/reference-1) < Decimal('1e-15')
    assert sqrt(1e16+1)-sqrt(1e16) == 0
code/python/catastrophic_cancellation_numpy.py
import numpy as np
from decimal import Decimal, localcontext
if __name__ == '__main__':
    x = np.array([1., 1e8, 1e16, 1e100, 1e300], dtype=np.float64)
    naive = np.sqrt(x+1)-np.sqrt(x)
    stable = np.reciprocal(np.sqrt(x+1)+np.sqrt(x))
    assert naive[2] == 0 and np.all(stable > 0)
    with localcontext() as ctx:
        ctx.prec = 450
        for value, answer in zip(x, stable):
            exact_x = Decimal.from_float(float(value))
            reference = 1/((exact_x+1).sqrt()+exact_x.sqrt())
            assert abs(Decimal.from_float(float(answer))/reference-1) < Decimal('1e-15')
    print('naive', naive, 'stable', stable)

Explore: predict the first lost operation

Start with small x, then the lost-subtraction preset. Predict whether x+1 itself changes before inspecting either square root. Increase x and compare the true-reference interval with both computed answers. Observe that cancellation can appear before every later range limit is reached.

Try an invalid negative x: the model rejects the experiment because the specified real function uses sqrt(x). Reset restores the canonical exact input and immutable trace. Keyboard entry and pointer presets reach the same state; the replay selects recorded intermediates rather than recomputing an alternative path.

Common mistakes and counterexamples

Subtraction is not universally inaccurate. For represented floating operands, subtraction can even be exact under appropriate conditions; the issue here is the information already lost while forming the operands. A small difference is also not itself proof that the mathematical problem is ill-conditioned.

An algebraic rearrangement can improve this evaluation without improving the conditioning of a different question. It is not a universal repair for arbitrary cancellation, undefined domains or overflow. In a quadratic-root implementation, rationalization likewise requires care about root signs, zero denominators, scale and the representability of intermediates; this chapter does not implement a general quadratic solver.

Numerical considerations

The supported range is the intended exact interval 0≤x≤1e300. It keeps the square-root sum finite and its reciprocal representable in binary64. Extending the implementation to arbitrary finite or infinite x would require additional range and exceptional-value policies, not simply reusing the current formula.

For each current input, exact rational endpoints bound the true result and the signed error of each numerical answer. For independent comparisons, use 450-digit Decimal arithmetic on hand-worked examples and widely separated scales; allow a small actual-value ULP difference when comparing platform square-root results. No tolerance can turn the naive zero into the positive mathematical answer.

Rationalization still uses rounded input, addition, roots, denominator and division. It reduces the cancellation mechanism but does not promise an exactly rounded answer for all inputs. The error intervals preserve that remaining limitation.

Engineering and ML connections

Difference formulas appear in finite differences, norms, loss changes and probability tails. A small difference between large rounded values deserves an error analysis before interpreting it as a reliable signal. Search for a mathematically justified alternative, check its domain and range, then compare against an independent reference on the inputs you actually support.

Inspect the corresponding representation and error policy before interpreting a computed value.

Exercises

Predict first, then calculate or test the stated claim. Every answer includes corrective feedback and a worked solution.

calculation

Exact zero input

At x=0, give sqrt(x+1)−sqrt(x).

calculation

The rounded denominator

Both computed roots equal 100000000. Give naive subtraction, then the rationalized result as a fraction.

calculation

An error interval

The real result is in [1/10,11/100], while q=1/8. Give lower then upper bounds for q−true.

explanation

What rationalization fixes

Why does the reciprocal-of-sum form help here?

Choose one answer

explanation

A zero computational result

At x=1e16 the naive result is zero. What is the true mathematical result?

Choose one answer

Summary and checkpoints

Derive the conjugate identity, reproduce the lost increment and zero subtraction at 1e16, and interpret signed error enclosures. Explain why the stable alternative helps this evaluation, why it still rounds, and why the stated domain/range remains part of its contract.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available