s LearnSqueak.com

NUMERIC ALGORITHMS · NESTED MULTIPLICATION

Horner’s method: evaluate polynomials with a running result

Turn polynomial coefficients into a compact Squeak Smalltalk calculation, trace nested multiplication, and test exact values, derivatives and floating-point limits.

8 Workspace checkpoints55 exact assertionsNative trace replay

Before you start

Use native Squeak 6.1 and a Workspace. These are eight independent expressions: select an entire code block, including its temporary-variable declaration, and choose Print it. Do not concatenate the blocks or file in the whole checkpoint collection. No extra package, network access or persistent application data is needed. This is not an installed SqueakJS demo.

Review blocks and closures, collections and exact Fractions. This tutorial concerns a known polynomial represented by numeric coefficients, not the site’s formula parser or spreadsheet.

Download all eight checkpoint expressions, the standalone 55-assertion test expression, or the complete source kit.

01 · Choose a coefficient convention

Our array lists coefficients from the highest power down to the constant. #(2 -3 0 5) means 2x³ − 3x² + 0x + 5. The zero is a placeholder, not disposable punctuation: removing it changes the polynomial. These array positions are Smalltalk’s one-based positions, not powers. This lesson evaluates a polynomial at a supplied x; it neither parses a formula string nor solves for its roots.

Independent Workspace expression · select all, then Print it
| coefficients |
coefficients := #(2 -3 0 5).
{coefficients size - 1. coefficients last}

Check: Print it shows #(3 5): the represented degree is three and the constant is five. A leading zero would make the actual mathematical degree smaller; this simple representation does not normalize leading zeros.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Choose a coefficient convention; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

02 · Write the nested form first

Factor x out of the nonconstant terms repeatedly: 2x³ − 3x² + 5 becomes ((2x − 3)x + 0)x + 5. At x = 2, start with 2, then produce 1, 2 and finally 9. Parentheses make the intended grouping visible. In Smalltalk, binary messages have equal precedence and run left to right; do not assume the precedence rules of a school algebra expression or another programming language.

Independent Workspace expression · select all, then Print it
| x |
x := 2.
((((2 * x) - 3) * x) + 0) * x + 5

Check: The answer is 9. Change only x to 3 and expect 32. Each new coefficient is added after multiplying the previous running result by x.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Write the nested form first; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

03 · Package the recurrence in a block

inject:into: walks a collection while carrying one accumulator. Initialize it with the first coefficient, then consume allButFirst. The block takes two arguments, the coefficient array and x. After consuming the first k coefficients, the accumulator equals the polynomial described by that prefix. Multiplying by x shifts its terms up one power; adding the next coefficient restores the invariant for the longer prefix.

Independent Workspace expression · select all, then Print it
| evaluate |
evaluate := [:terms :argument |
 terms isEmpty ifTrue: [Error signal: 'At least one coefficient is required'].
 terms allButFirst inject: terms first
  into: [:accumulator :coefficient | (accumulator * argument) + coefficient]].
evaluate value: #(2 -3 0 5) value: 2

Check: This independent Workspace expression returns 9. Read value:value: as one two-keyword message to the block. The initializer avoids one redundant multiply-by-zero operation that a zero seed would perform.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Package the recurrence in a block; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

04 · Keep a trace instead of guessing

A trace is useful when an answer is wrong. It records the accumulator before the loop and after each coefficient. Here it also explains the four-state native replay below. The algorithm’s working state is a single number; the OrderedCollection is extra diagnostic storage, not a requirement of Horner’s method.

Independent Workspace expression · select all, then Print it
| coefficients x accumulator trace |
coefficients := #(2 -3 0 5). x := 2.
accumulator := coefficients first.
trace := OrderedCollection with: accumulator.
coefficients allButFirst do: [:coefficient |
 accumulator := (accumulator * x) + coefficient.
 trace add: accumulator].
trace asArray

Check: Expect #(2 1 2 9). Before changing the algorithm, compare the input order, the zero coefficient and the chosen x. The visual trace uses these same values.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Keep a trace instead of guessing; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

Replay the running result

NATIVE SQUEAK CAPTURE
Native Squeak Horner trace initially highlighting coefficient two and accumulator two
Four actual native Morphic captures show the computed states 2, 1, 2 and 9. Captured-state replay, not mouse footage.

Download the visual trace expression, open it as text in Squeak and Do it as a whole. Change stage := 0. to 1, 2 or 3 to inspect later states. Close the old window before opening another. The drawing needs 1000 × 430 pixels and has no timer or network activity. The zero coefficient is consumed just like every other coefficient.

05 · Handle constants and invalid input

A one-element array is a constant polynomial, so the loop performs no work. This lesson deliberately rejects an empty array rather than silently treating it as zero. That makes missing input visible. A different API could define an empty polynomial as zero, but it must say so consistently. The test catches only the intended Error to demonstrate that contract.

Independent Workspace expression · select all, then Print it
| evaluate rejected |
evaluate := [:terms :argument |
 terms isEmpty ifTrue: [Error signal: 'At least one coefficient is required'].
 terms allButFirst inject: terms first
  into: [:accumulator :coefficient | (accumulator * argument) + coefficient]].
rejected := [evaluate value: #() value: 2. false]
 on: Error do: [:error | true].
{evaluate value: #(7) value: 999. rejected}

Check: Expect #(7 true). The block assumes numeric coefficients and numeric x; it is not a general input-validation library. Keep user-entered text parsing separate from numeric evaluation.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Handle constants and invalid input; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

06 · Preserve exact arithmetic when possible

Squeak integers and Fractions let us test the recurrence without introducing floating-point rounding. At x = 1/2 the chosen polynomial is exactly 9/2. Horner’s method changes the order of operations, not the mathematical value. Exact arithmetic is convenient for teaching and tests, but growing integers and fractions can have substantial cost; a count of arithmetic operations is not a complete runtime prediction.

Independent Workspace expression · select all, then Print it
| evaluate answer |
evaluate := [:terms :argument |
 terms isEmpty ifTrue: [Error signal: 'At least one coefficient is required'].
 terms allButFirst inject: terms first
  into: [:accumulator :coefficient | (accumulator * argument) + coefficient]].
answer := evaluate value: #(2 -3 0 5) value: (1 / 2).
{answer. answer = (9 / 2). answer isInteger}

Check: Expect an array containing the Fraction 9/2, true, and false. The exact printed Fraction spelling can include parentheses in Squeak; the assertion compares numeric objects, not screen typography.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Preserve exact arithmetic when possible; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

07 · Evaluate a derivative with the same block

To differentiate a polynomial, multiply each nonconstant coefficient by its power and drop the constant. The coefficients #(2 -3 0 5) become #(6 -6 0), representing 6x² − 6x. This is coefficient transformation followed by ordinary evaluation, not numerical differentiation. A constant polynomial needs the explicit derivative representation #(0).

Independent Workspace expression · select all, then Print it
| coefficients degree derivative evaluate |
coefficients := #(2 -3 0 5).
degree := coefficients size - 1.
derivative := degree = 0
 ifTrue: [#(0)]
 ifFalse: [(1 to: degree) collect: [:index |
  (coefficients at: index) * (degree - index + 1)]].
evaluate := [:terms :argument |
 terms isEmpty ifTrue: [Error signal: 'At least one coefficient is required'].
 terms allButFirst inject: terms first
  into: [:accumulator :coefficient | (accumulator * argument) + coefficient]].
{derivative. evaluate value: derivative value: 2}

Check: Expect derivative coefficients #(6 -6 0) and value 12. Check the power formula: array index 1 corresponds to degree, not exponent one. Try a constant and confirm its derivative evaluates to zero.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Evaluate a derivative with the same block; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

08 · Compare floating results with a tolerance

A Float input generally produces a rounded result. A tolerance test asks whether the difference is small enough for this example, rather than promising universal accuracy. The decimal 0.1 is not exactly represented as a binary floating-point number. Horner evaluation uses fewer arithmetic operations than separately calculating every power, but cancellation and ill-conditioned problems can still magnify relative error, especially near roots.

Independent Workspace expression · select all, then Print it
| evaluate approximate exact tolerance |
evaluate := [:terms :argument |
 terms isEmpty ifTrue: [Error signal: 'At least one coefficient is required'].
 terms allButFirst inject: terms first
  into: [:accumulator :coefficient | (accumulator * argument) + coefficient]].
approximate := evaluate value: #(2 -3 0 5) value: 0.1.
exact := evaluate value: #(2 -3 0 5) value: (1 / 10).
tolerance := 0.000000000001.
{exact. (approximate - exact asFloat) abs < tolerance}

Check: Expect the exact Fraction 1243/250 and true. The chosen absolute tolerance is specific to values around five. For values across very different scales, combine a justified absolute floor with a relative tolerance.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Compare floating results with a tolerance; evaluated expression and highlighted result
Genuine Squeak Workspace after Print it. The selected text is the result, not a mock-up.

Test against a different calculation

The standalone test expression repeats all eight published checkpoints, then compares Horner’s result with a separately written power-sum evaluator for six coefficient arrays and seven inputs each. It also checks the zero polynomial, an empty array, zero input, negative input and another positive input: 55 assertions in total. Open the test file as text, select the complete expression and Print it; expect 55. A failed condition signals an Error. These are direct assertions, not a claimed SUnit suite.

What the operation count does and does not mean

With n + 1 coefficients, the recurrence performs n multiplications and n additions. Repeatedly building each power from scratch is unnecessary. However, our readable allButFirst version creates a collection of the remaining coefficients, so the implementation has linear temporary collection storage. An index loop from 2 through the coefficient count can avoid that copy. Neither form makes arbitrary-precision arithmetic constant-cost, and neither makes polynomial evaluation a root-finding algorithm.

Do not claim a speedup from this operation count alone: measure representative inputs in Squeak if runtime matters. Very high degree, enormous exact numerators, or cancellation near a root may need a more suitable representation or numerical method. Horner’s method is a good default computation pattern, not a promise of exact Float results.

Try three small extensions

  1. Change the input to 3 and verify 32. Then use −1 and explain why the result is zero without changing the algorithm.
  2. Rewrite the evaluator with an index loop and retain all 55 tests. Preserve the explicit empty-array contract and the one-element constant case.
  3. Extract derivative-coefficient creation into a block. Test a constant, a linear polynomial and the cubic here before adding it to any plotting application.

Keep transformation, evaluation and display separate. The derivative block should return coefficients, the evaluator should return a number, and the Morphic view should only display computed results.

Sources and next steps

Douglas Wilhelm Harder’s University of Waterloo explanation of polynomial evaluation describes nested multiplication and its arithmetic count. This article’s Smalltalk expressions, test matrix and native visual trace are original. Source reviewed 26 October 2026. Official Squeak documentation provides language and environment references.

Continue with measuring real Squeak work, SUnit or Bézier curves. A Bézier representation has its own geometric evaluation strategy; do not assume that converting every problem to monomial coefficients is best.