A13 · Lesson 9 · Lab: floating point and roots in code
Measuring spacing, summing carefully, and finding polynomial roots
Lessons 1 to 8 described floating point, cancellation, conditioning and root finding with formulas. This lab checks each with code. You'll ask NumPy for the spacing of doubles and half-precision numbers, watch a long sum drift and repair it with Kahan's compensated summation, fix a quadratic formula that loses a root, find every root of a cubic by Newton's method with deflation, and watch a polynomial's roots scatter when one coefficient changes in its fifth digit.
- A sum of n numbers, each rounded to double precision, can drift by up to about relative to the total, with ; typical drift is closer to .
- The curves show both against n, and the flat line shows Kahan summation's bound, which doesn't grow with n.
- At a million terms, naive summation is good to about to relative; Kahan stays near .
Predict
In double precision, you add 0.1 to a running total one million times. How far is the result from 100 000?
About . Each addition rounds the growing total to its spacing, which near is , and the roundings mostly lean the same way, because 0.1 itself isn't exact in binary. Kahan's compensated sum, or math.fsum, carries the lost low-order bits along and lands on the correctly rounded total.
Name it
Tools
np.spacing(x)gives the gap from x to the next representable number of x's type;np.float16(x),np.float32(x)make lower-precision values.math.fsumadds a list of floats exactly and rounds once.np.poly(roots)builds coefficients from roots, andnp.roots(coeffs)finds roots through the companion matrix.
Kahan summation
Keep a correction c of what the last addition lost:
y = x - c; t = s + y; c = (t - s) - y; s = t
In exact arithmetic c would be 0; in floating point, recovers the low-order part of y that didn't fit into t, to be added back next time.
Newton with deflation
Run Newton's method with Horner's rule on the polynomial, divide out the root found, repeat on the quotient, and polish each root with a couple of Newton steps on the original polynomial.
Worked example
What are the spacings of doubles near 1 and 1000, and of half-precision numbers near 1 and 1000?
Show the solution
- Doubles.
np.spacing(1.0)is andnp.spacing(1000.0)is : the same 53 significant bits, scaled by the power of two. - Half precision.
np.spacing(np.float16(1))is andnp.spacing(np.float16(1000))is 0.5. - What that does to a sum. A float16 accumulator holding a total near 1000 can't register an increment of 0.2: it rounds back to the same value. That's the stalled-clock problem of lesson 1, in a format used for neural network training.
Answer doubles are spaced near 1 and near 1000; half-precision numbers are spaced near 1 and 0.5 near 1000.
Worked example
Compute the small root of two ways.
Show the solution
- The textbook formula. That's wrong by 25%: the square root equals to almost every digit, and the subtraction leaves only rounding noise.
- The large root first. It has no cancellation:
- The small root from the product of the roots. This is correct to full precision.
Answer the textbook formula gives , wrong by 25%; dividing c by the large root gives , correct to full precision.
Check
What does np.spacing return for x = 50 in a format with 24 significant bits?
Check
What is the small root of , computed stably?
Check
Add 0.1 one million times, naively into naive and with Kahan's compensated summation into kahan. Set exact to math.fsum([0.1] * 1000000).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write small_root(b, c) returning the small root of (b > 0) without cancellation. Set bad to the textbook formula's value for , c = 1, and good to yours.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write horner(a, x) returning for coefficients a (highest power first) and deflate(a, r) returning the quotient after dividing by . Find all roots of by Newton from 0 with deflation, polishing each on the original. Set roots.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Build the coefficients of with np.poly, add 0.0005 to the coefficient, and find the roots with np.roots. Set leftmost to the real part of the leftmost root and max_imag to the largest imaginary part.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Set s1 and s1000 to np.spacing of 1.0 and 1000.0 in float64, and h1 and h1000 to the same in float16. Then set stuck to True if adding np.float16(0.2) to np.float16(1000) leaves it unchanged.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Explain why
Why does Kahan's correction capture exactly what an addition lost?
When s and y are added, the result t keeps only the high-order part of the true sum; the low-order bits of y that fall below t's last place are rounded away. Subtracting s from t then recovers the part of y that actually made it into t, and this subtraction is exact, because t and s are close. Subtracting y from that leaves minus the part of y that was lost, again exactly in typical cases. Feeding that correction into the next addition puts the lost bits back, so the running sum carries an extra word of precision and the error no longer grows with the number of terms.
Practice
Keep practicing
4 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.