Polynomials and decimal-string integers
| Problem | Evaluate polynomials, build them from their roots and find their roots; and do exact integer arithmetic on numbers too large for any machine word |
| Devised by | William Horner (1819), and Qin Jiushao (1247), nested evaluation; Ferdinand Georg Frobenius, the companion matrix; James Wilkinson (1959), the ill-conditioning of polynomial roots; schoolbook long arithmetic, as taught since the Middle Ages |
| Accuracy | Horner’s rule is backward stable; companion-matrix roots are accurate to roughly the coefficients’ precision times the roots’ condition, which grows explosively for clustered roots (figure below); decimal-string arithmetic is exact |
| Cost | Horner ; roots (an eigenvalue problem); string addition , multiplication , division for -digit numbers |
| Read first | Divisibility and modular arithmetic |
| API | polynomial_eval, polynomial_from_roots, polynomial_roots, TextCodedInteger |
Overview
A polynomial is stored by its coefficients, highest power first. Horner’s rule evaluates it with multiplications and additions, as . Multiplying out builds it from its roots. Going back, from coefficients to roots, is an eigenvalue problem: the roots are the eigenvalues of the companion matrix, which is how MATLAB’s and NumPy’s roots work. That direction is treacherous,
as Wilkinson’s famous polynomial shows. Separately, TextCodedInteger stores an integer as its decimal digits and does arithmetic on them as taught in school. It is unbounded and exact, but slow: a teaching implementation of arbitrary precision.
Where it is used
Polynomials and big integers are the objects of exact computation.
- Polynomials. Characteristic polynomials of systems, transfer functions in control and filter design, and roots from factored forms.
- Exact integer arithmetic. Arithmetic on numbers with thousands of digits, needed in cryptography, computer algebra and checking the results of floating-point computations.
- Evaluation. Horner’s rule evaluates a polynomial with the fewest operations and good numerical behaviour.
History
Nested evaluation appears in Qin Jiushao’s Mathematical Treatise in Nine Sections (1247) and was rediscovered by William Horner (1819) for solving equations. The companion matrix, with ones on the subdiagonal and the negated coefficients in its last column, is credited to Frobenius. In the 1950s James Wilkinson computed the roots of on the Pilot ACE and found that a change of in one coefficient moved the roots 10 to 19 into the complex plane. He called it “the most traumatic experience in my career as a numerical analyst”. It made the conditioning of polynomial roots a classic topic. Computer algebra systems and libraries such as GMP provide fast arbitrary-precision integers; the decimal-string version here favours transparency over speed.
The idea
Horner’s rule and building from roots
Horner’s rule needs no powers and accumulates little rounding error: the computed value is the exact value of a polynomial with coefficients perturbed by a few units in the last place. Building from roots multiplies in one linear factor at a time, each a shift-and-subtract on the coefficient vector.
Roots from the companion matrix
The matrix with ones below the diagonal and last column has characteristic polynomial . Its eigenvalues, from the QR algorithm, are the roots. The eigenvalue solver is backward stable, so the roots are exact for a nearby polynomial. Whether they are close to the true roots depends on how sensitive the roots are to the coefficients. For Wilkinson’s polynomial, with roots , the sensitivity grows enormously with :
Figure 22.4. Wilkinson's polynomial.
At degree 20 the coefficients reach , and their rounding alone moves the larger roots by order one. Representing a polynomial by its roots or values, not its expanded coefficients, avoids the problem.
Decimal-string integers
TextCodedInteger holds a sign and decimal digits, normalised so that each value has one representation. Addition and subtraction work digit by digit with carries and borrows. Multiplication is the schoolbook convolution of digits. Division is long division, producing one quotient digit at a time by repeated subtraction. The quotient truncates toward zero, and the remainder has the dividend’s sign, like Rust’s integers. The type implements the num_traits integer traits, so generic numeric code can use it.
Table 22.3. Large factorials: size and time.
| value | decimal digits | digits | time to compute (ms) |
|---|---|---|---|
| 20! | 19 | 243290200817…640000 | 0.01 |
| 50! | 65 | 304140932017…000000 | 0.02 |
| 100! | 158 | 933262154439…000000 | 0.07 |
| 200! | 375 | 788657867364…000000 | 0.30 |
The time grows roughly quadratically with the number of digits, as schoolbook multiplication should.
Algorithm
Evaluation by Horner’s rule, with coefficients from the highest power down: set ; for each coefficient in turn, set . The result is : multiplications and additions for degree .
Building a polynomial from its roots: start with the single coefficient 1, the polynomial . For each root , multiply the polynomial by : the new coefficient is , where are the old coefficients (taken as zero outside their range). Working from the highest index down lets the update be done in place.
Roots: form the companion matrix and compute its eigenvalues with the general eigensolver; see polynomial roots.
Arithmetic on decimal strings.
- Addition: add the digits from the least significant end, carrying 1 whenever a sum reaches 10. Numbers of opposite sign are subtracted instead, the smaller in magnitude from the larger, with borrows.
- Multiplication: for each pair of digits, one from each number, at positions and , add their product into position of the result; then propagate the carries.
- Division: long division. Bring down one digit of the dividend at a time, and find the quotient digit by subtracting the divisor from the running remainder as many times as it will go.
Multiplication and division of numbers with and digits cost digit operations.
Implementation
let order = coeffs.len() - 1;
let mut companion = Array2::from_elem((order, order), Complex::new(0.0, 0.0));
for row in 1..order {
companion[[row, row - 1]] = Complex::new(1.0, 0.0);
}
for row in 0..order {
companion[[row, order - 1]] = -coeffs[order - row].to_complex() / lead;
}
- Polynomial functions take real or complex coefficients (anything implementing
IsAnalytic) and evaluate at complex points.
In practice
//! Polynomials by their coefficients and roots, and decimal-string integers of any size.
use lib_jsl_number_theory::polynomial::{polynomial_eval, polynomial_from_roots, polynomial_roots};
use lib_jsl_number_theory::text_coded_integer::TextCodedInteger;
use num_complex::Complex;
fn main() {
// x³ − 6x² + 11x − 6 = (x − 1)(x − 2)(x − 3), coefficients in descending powers.
let p = [1.0, -6.0, 11.0, -6.0];
println!("p(4) = {}", polynomial_eval(&p, Complex::new(4.0, 0.0)));
let mut roots: Vec<f64> = polynomial_roots(&p).unwrap().iter().map(|r| r.re).collect();
roots.sort_by(f64::total_cmp);
println!("roots of p: {:.12?}", roots);
let q = polynomial_from_roots(&[Complex::new(0.0, 1.0), Complex::new(0.0, -1.0)]);
println!("(x − i)(x + i) has coefficients {:?}", q.iter().map(|c| c.re).collect::<Vec<_>>());
// 2^100 and 30! in decimal-string arithmetic.
let mut power = TextCodedInteger::new(1);
for _ in 0..100 {
power = power * TextCodedInteger::new(2);
}
let mut factorial = TextCodedInteger::new(1);
for k in 2..=30 {
factorial = factorial * TextCodedInteger::new(k);
}
println!("2^100 = {power}");
println!("30! = {factorial}");
println!("30! / 2^100 = {} remainder {}", factorial.clone() / power.clone(), factorial % power);
}
p(4) = 6+0i
roots of p: [1.000000000000, 2.000000000000, 3.000000000000]
(x − i)(x + i) has coefficients [1.0, 0.0, 1.0]
2^100 = 1267650600228229401496703205376
30! = 265252859812191058636308480000000
30! / 2^100 = 209 remainder 313884364491113723497510076416
Strengths
- Standard, robust evaluation and root finding for moderate degrees.
- Exact integers of any size with no dependencies, readable digit by digit.
Weaknesses
- Roots of high-degree or clustered-root polynomials are ill-conditioned in the coefficient basis; no polishing or multiplicity detection.
- Decimal-string arithmetic is orders of magnitude slower than binary arbitrary precision (no Karatsuba or FFT multiplication).
Exercises
- Show that Horner’s rule uses multiplications, and that no general method uses fewer for arbitrary coefficients.
- Verify that the companion matrix’s characteristic polynomial is .
- Compute the derivative of the root of Wilkinson’s polynomial with respect to the coefficient of , and evaluate it for .
- Show that the roots of move by : a double root is infinitely sensitive.
- Implement Karatsuba multiplication on decimal strings and find the crossover length.
Hints and answers
- has multiplications and additions. That no method using only additions and multiplications can do better for arbitrary coefficients was proved by Pan (1966): multiplications are necessary as well as sufficient.
- Expand along the row or column that carries the coefficients; each step contributes one term .
- If the coefficient of is perturbed, gives . For , , so the derivative is .
- has roots (or ): the change is , so is unbounded as .
- Karatsuba replaces four half-size multiplications by three. The crossover with schoolbook multiplication is typically a few dozen to a few hundred digits, depending on the implementation; measure it.
Further reading
- J. H. Wilkinson, “The perfidious polynomial”, in G. H. Golub (ed.), Studies in Numerical Analysis, MAA, 1984, 1–28.
- A. Edelman and H. Murakami, “Polynomial roots from companion matrix eigenvalues”, Mathematics of Computation 64 (1995) 763–776.
- D. E. Knuth, The Art of Computer Programming, vol. 2, Seminumerical Algorithms, 3rd ed., Addison-Wesley, 1997, sections 4.3 and 4.6.4.