s LearnSqueak.com

EXACT ALGORITHMS · LINEAR SYSTEMS

Gaussian elimination: solve small systems with exact row operations

Build an exact linear-system solver in Squeak Smalltalk, swap zero pivots, distinguish unique and nonunique outcomes, and verify solutions with rational residuals.

9 Workspace checkpoints2,757 native assertions8-state row-operation replay

Before you start

How can three equations determine three unknowns? Instead of trying values, rewrite the equations until the last one has only one unknown. Then work backward. This lesson builds that transformation as ordinary Smalltalk arrays and blocks, using exact Integer and Fraction arithmetic throughout.

Open a Workspace in native Squeak 6.1. Copy one complete checkpoint, select all of it and choose Print it. The nine expressions are independent: later checkpoints repeat the complete solver so they work without hidden setup. Do not concatenate them into one expression, and do not file in the checkpoint collection. Squeak may display Fractions in parentheses and Symbols with an extra #; the expected expressions below denote the same values, not a required whitespace format.

You need basic arrays, blocks, loops and message precedence. Review collections, blocks and closures or the Fraction Lab first. That lab explains rational objects and scaling; here the new problem is preserving an entire system of equations while finding its unknowns.

Download all nine checkpoints, the assertion expression, or the native source kit. No package installation, network connection, saved image changes or custom classes are required.

Choose an exact, deliberately small contract

The input is a nonempty Array of n rows. Each row is an Array of n + 1 Integer or Fraction values: n coefficients followed by one right-hand side (RHS). Thus the coefficient matrix is square, while the stored augmented matrix has one extra column. The second block argument must be exactly true or false and controls trace snapshots. An invalid shape, a Float, a nonnumeric entry or a non-Boolean trace flag signals an Error before row mutation.

The output is an Array with four slots:

  1. Status: #unique, #underdetermined or #inconsistent.
  2. Solution: an Array in variable-column order, or nil when there is no unique solution.
  3. Echelon rows: new mutable arrays containing the transformed augmented matrix.
  4. Trace: an Array of copied states, or an empty Array when tracing is false.

#underdetermined means consistent but with free variables: infinitely many rational solutions, not “the solver did not finish.” #inconsistent means a contradiction, so there is no solution. Both cases have a singular coefficient matrix; “singular” by itself does not tell them apart. We classify them but do not return a parameterized family of solutions. Rectangular systems, least-squares fitting, matrix inversion and approximate numerical solving are outside this contract.

01 · Store equations as augmented rows

For 0x + 2y + z = 7, 2x + y - z = 1 and x - y + 2z = 5, keep each right-hand side in the last column. Arrays are one-based: the entry at row 2, column 3 is -1, and column 4 is the RHS.

The order is a promise: column 1 always means x, column 2 means y and column 3 means z. A row exchange changes equation order, not variable order. The fourth entry is data on the other side of the equals sign; it must participate in every row operation.

Nested literal arrays are convenient for the initial data, but elimination writes into rows. The complete solver therefore creates a new outer collection and copies each row. Merely copying the outer Array would leave both matrices pointing at the same mutable row objects.

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

Expected value: #(3 4 -1 1)

Check: Read (rows at: 2) at: 3 as two messages: select a row, then select its coefficient.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Store equations as augmented rows, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

02 · Eliminate one coefficient with an exact multiplier

Use pivot row #(2 1 -1 1) to remove the first coefficient of #(1 -1 2 5). The multiplier is 1/2. Subtract that multiple from every entry, including the RHS. Ordinary / keeps this calculation rational; // would be wrong.

Why this multiplier? Its first product is (1/2) × 2 = 1, exactly the coefficient we want to remove. The replacement row is oldRow − multiplier × pivotRow. The pivot row itself is unchanged, so adding the same multiple back can reverse the operation. That reversibility is why we preserve the solution set.

Changing only the first coefficient to zero would not be elimination: it would invent a different equation. All later coefficients and the RHS must be updated by the same arithmetic. The full solver starts its inner loop at the current column because earlier pivot columns are already zero in the rows it is changing.

Independent Workspace expression · select all, then Print it
| pivot row factor |
pivot := #(2 1 -1 1). row := #(1 -1 2 5) copy.
factor := row first / pivot first.
1 to: row size do: [:j |
 row at: j put: ((row at: j) - (factor * (pivot at: j)))].
{factor. row}

Expected value: {1 / 2. {0. -3 / 2. 5 / 2. 9 / 2}}

Check: The new equation is -(3/2)y + (5/2)z = 9/2. The original solution still satisfies it.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Eliminate one coefficient with an exact multiplier, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

03 · Repair a zero pivot by swapping whole rows

The first equation has a zero x coefficient. Search at or below the current row for a nonzero value in that column, then exchange entire augmented rows. Swapping only coefficients but not the RHS would change the system.

The search is deterministic: choose the first nonzero candidate, not the largest magnitude. For exact rational arithmetic this avoids division by zero without a rounding-error threshold. It is not the partial-pivoting policy normally used to control numerical error in Float solvers. Do not convert this lesson to Float simply by removing its validation.

Independent Workspace expression · select all, then Print it
| matrix pivot temp |
matrix := #(#(0 2 1 7) #(2 1 -1 1) #(1 -1 2 5)) collect: [:row | row copy].
pivot := (1 to: matrix size)
 detect: [:r | ((matrix at: r) at: 1) ~= 0] ifNone: [0].
temp := matrix first.
matrix at: 1 put: (matrix at: pivot). matrix at: pivot put: temp.
{pivot. matrix first. matrix second}

Expected value: {2. #(2 1 -1 1). #(0 2 1 7)}

Check: This small experiment knows a pivot exists. The complete solver handles the no-pivot case rather than indexing row zero.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Repair a zero pivot by swapping whole rows, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

04 · Solve the triangular system from the bottom

After elimination, the last equation contains only z. Solve it first, then subtract known contributions while moving upward. Parentheses keep subtraction separate from multiplication: Smalltalk binary messages otherwise have equal precedence.

The third equation says (13/4)z = 39/4, giving z = 3. The second then says 2y + 3 = 7, giving y = 2. Finally 2x + 2 − 3 = 1 gives x = 1. The answer Array keeps the original variable order even though values were discovered in reverse order.

Independent Workspace expression · select all, then Print it
| triangular answer rhs |
triangular := {#(2 1 -1 1). #(0 2 1 7). {0. 0. 13 / 4. 39 / 4}}.
answer := Array new: 3.
3 to: 1 by: -1 do: [:i |
 rhs := (triangular at: i) last.
 i + 1 to: 3 do: [:j |
  rhs := rhs - (((triangular at: i) at: j) * (answer at: j))].
 answer at: i put: rhs / ((triangular at: i) at: i)].
answer

Expected value: #(1 2 3)

Check: At i = 3 the inner range is empty, so no unsolved entry is read. At i = 1, y and z are already available.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Solve the triangular system from the bottom, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

Watch the equations become triangular

NATIVE SQUEAK CAPTURE
Native Squeak augmented matrix before elimination, with three unsolved solution entries
Eight genuine Morphic captures replay computed solver states. This is a captured-state replay, not mouse footage or a browser implementation.

The orange column is the RHS. Blue coefficient cells are exact zeros, and green cells are nonzero. The values come from checkpoint 9’s trace; the renderer does not contain a second hand-written list of answers. Watch row 1 exchange with row 2, the lower-left coefficients become zero, then the known solution entries fill from right to left.

Download the complete native visual expression. Open it as text and Do it as a whole. Change stage := 1. to a number from 2 through 8 to open another computed state; close the previous window first. It opens a fixed 1080 × 580 Morphic window. There is no timer, animation process, persistent data or network activity to clean up. Closing the window removes the view.

05 · Combine validation, forward elimination and back substitution

The solver copies every input row before mutation. nextRow counts accepted pivots; col scans variable columns. Keeping them separate lets a missing pivot column be skipped, which is essential for classifying singular systems correctly. The four result slots are status, solution-or-nil, echelon rows and optional trace.

Read the large block in four passes. First validate and copy. Next scan columns, find a pivot, exchange rows if necessary, and remove the coefficients below that pivot. Then look for a contradictory zero-coefficient row and count pivots. Only a unique system enters back substitution. The final array is the block result; no nonlocal return is needed.

The sentinel 0 means “no candidate found” because real row indexes begin at 1. It is checked before any indexing. On a missing pivot, col advances but nextRow does not. When all n columns have pivots, there were no skipped columns, so the pivots are exactly the diagonal entries used by the reverse loop. This is why rank detection must precede back substitution.

Independent Workspace expression · select all, then Print it
| solve result |
solve := [:input :keepTrace |
 | n matrix solution trace record nextRow pivot temp factor status rhs |
 (input isArray and: [input notEmpty])
  ifFalse: [Error signal: 'Use a nonempty Array of augmented rows'].
 ((keepTrace == true) or: [keepTrace == false])
  ifFalse: [Error signal: 'The trace flag must be true or false'].
 n := input size.
 (input allSatisfy: [:row | row isArray and: [row size = (n + 1)]])
  ifFalse: [Error signal: 'Each of n rows needs n coefficients and one RHS'].
 (input allSatisfy: [:row | row allSatisfy: [:v |
  v isInteger or: [v isFraction]]])
  ifFalse: [Error signal: 'Use only Integer or Fraction entries'].
 matrix := input collect: [:row | row copy].
 solution := Array new: n. trace := OrderedCollection new.
 record := [:label | keepTrace ifTrue: [trace add:
  {label. matrix collect: [:row | row copy]. solution copy}]].
 record value: 'Initial augmented matrix'. nextRow := 1.
 1 to: n do: [:col |
  pivot := (nextRow to: n)
   detect: [:r | ((matrix at: r) at: col) ~= 0] ifNone: [0].
  pivot = 0
   ifTrue: [record value: 'No pivot in column ', col printString]
   ifFalse: [
    pivot ~= nextRow ifTrue: [
     temp := matrix at: nextRow.
     matrix at: nextRow put: (matrix at: pivot). matrix at: pivot put: temp.
     record value: 'Swap rows ', nextRow printString, ' and ', pivot printString].
    nextRow + 1 to: n do: [:r |
     factor := ((matrix at: r) at: col) / ((matrix at: nextRow) at: col).
     col to: n + 1 do: [:j | (matrix at: r) at: j put:
      (((matrix at: r) at: j) - (factor * ((matrix at: nextRow) at: j))) ]].
    record value: 'Pivot column ', col printString, '; zeros below row ', nextRow printString.
    nextRow := nextRow + 1]].
 status := (matrix anySatisfy: [:row |
  ((1 to: n) allSatisfy: [:j | (row at: j) = 0]) and: [row last ~= 0]])
   ifTrue: [#inconsistent]
   ifFalse: [nextRow = (n + 1) ifTrue: [#unique] ifFalse: [#underdetermined]].
 status = #unique
  ifTrue: [n to: 1 by: -1 do: [:i |
   rhs := (matrix at: i) last.
   i + 1 to: n do: [:j | rhs := rhs - (((matrix at: i) at: j) * (solution at: j))].
   solution at: i put: rhs / ((matrix at: i) at: i).
   record value: 'Back substitute x', i printString]]
  ifFalse: [solution := nil].
 {status. solution. matrix. trace asArray}].
result := solve value: #(#(0 2 1 7) #(2 1 -1 1) #(1 -1 2 5)) value: false.
{result first. result second}

Expected value: {#unique. #(1 2 3)}

Check: false disables snapshots, not validation. Only a full set of pivots enters the diagonal back-substitution loop.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Combine validation, forward elimination and back substitution, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

06 · Accept Fraction inputs without changing the caller

Exactness is a contract, not a display format. This system includes fractional coefficients and RHS values and returns x = 1/2 and y = -2/3. Integer and Fraction objects are accepted; Float entries are rejected rather than silently mixed in.

The first equation is (1/2)x + (1/3)y = 1/36. Parenthesized fractions are numeric objects produced by ordinary division, not strings. They may simplify back to Integers during calculation. Both types belong to the exact domain; requiring every intermediate result to remain a Fraction would wrongly reject zero and whole answers.

The solver deliberately refuses 0.5 even though that particular Float is exactly representable. A uniform rational-input rule is easier to understand than allowing selected approximations. For measurement data, an approximate solver with a separate stability and tolerance policy would be a different lesson.

Independent Workspace expression · select all, then Print it
| solve rows before result |
solve := [:input :keepTrace |
 | n matrix solution trace record nextRow pivot temp factor status rhs |
 (input isArray and: [input notEmpty])
  ifFalse: [Error signal: 'Use a nonempty Array of augmented rows'].
 ((keepTrace == true) or: [keepTrace == false])
  ifFalse: [Error signal: 'The trace flag must be true or false'].
 n := input size.
 (input allSatisfy: [:row | row isArray and: [row size = (n + 1)]])
  ifFalse: [Error signal: 'Each of n rows needs n coefficients and one RHS'].
 (input allSatisfy: [:row | row allSatisfy: [:v |
  v isInteger or: [v isFraction]]])
  ifFalse: [Error signal: 'Use only Integer or Fraction entries'].
 matrix := input collect: [:row | row copy].
 solution := Array new: n. trace := OrderedCollection new.
 record := [:label | keepTrace ifTrue: [trace add:
  {label. matrix collect: [:row | row copy]. solution copy}]].
 record value: 'Initial augmented matrix'. nextRow := 1.
 1 to: n do: [:col |
  pivot := (nextRow to: n)
   detect: [:r | ((matrix at: r) at: col) ~= 0] ifNone: [0].
  pivot = 0
   ifTrue: [record value: 'No pivot in column ', col printString]
   ifFalse: [
    pivot ~= nextRow ifTrue: [
     temp := matrix at: nextRow.
     matrix at: nextRow put: (matrix at: pivot). matrix at: pivot put: temp.
     record value: 'Swap rows ', nextRow printString, ' and ', pivot printString].
    nextRow + 1 to: n do: [:r |
     factor := ((matrix at: r) at: col) / ((matrix at: nextRow) at: col).
     col to: n + 1 do: [:j | (matrix at: r) at: j put:
      (((matrix at: r) at: j) - (factor * ((matrix at: nextRow) at: j))) ]].
    record value: 'Pivot column ', col printString, '; zeros below row ', nextRow printString.
    nextRow := nextRow + 1]].
 status := (matrix anySatisfy: [:row |
  ((1 to: n) allSatisfy: [:j | (row at: j) = 0]) and: [row last ~= 0]])
   ifTrue: [#inconsistent]
   ifFalse: [nextRow = (n + 1) ifTrue: [#unique] ifFalse: [#underdetermined]].
 status = #unique
  ifTrue: [n to: 1 by: -1 do: [:i |
   rhs := (matrix at: i) last.
   i + 1 to: n do: [:j | rhs := rhs - (((matrix at: i) at: j) * (solution at: j))].
   solution at: i put: rhs / ((matrix at: i) at: i).
   record value: 'Back substitute x', i printString]]
  ifFalse: [solution := nil].
 {status. solution. matrix. trace asArray}].
rows := {{1 / 2. 1 / 3. 1 / 36}. {2. -1. 5 / 3}}.
before := rows collect: [:row | row copy].
result := solve value: rows value: false.
{result second. rows = before. result third first == rows first}

Expected value: {{1 / 2. -2 / 3}. true. false}

Check: Equality confirms the input values survived. Identity confirms the returned first row is not the caller's first row.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Accept Fraction inputs without changing the caller, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

07 · Tell no solution from more than one solution

A row with all-zero coefficients and nonzero RHS is a contradiction. If there is no contradiction but fewer than n pivots, at least one variable is free. Both have a singular coefficient matrix, but their solution sets differ. The solver reports these outcomes instead of dividing by zero or guessing free-variable values.

Subtracting twice the first row of the dependent example leaves 0x + 0y = 0: it adds no constraint. In the impossible example the same operation leaves 0x + 0y = 1: no values can satisfy it. The scan tests the coefficient columns separately from the RHS so these two rows cannot be confused.

nil is a return-contract marker here, not an unknown numeric value to multiply. Check the status before using the solution slot. A future extension could return free-variable descriptions for #underdetermined, but it should not silently choose all free variables to be zero and claim uniqueness.

Independent Workspace expression · select all, then Print it
| solve dependent impossible skipped |
solve := [:input :keepTrace |
 | n matrix solution trace record nextRow pivot temp factor status rhs |
 (input isArray and: [input notEmpty])
  ifFalse: [Error signal: 'Use a nonempty Array of augmented rows'].
 ((keepTrace == true) or: [keepTrace == false])
  ifFalse: [Error signal: 'The trace flag must be true or false'].
 n := input size.
 (input allSatisfy: [:row | row isArray and: [row size = (n + 1)]])
  ifFalse: [Error signal: 'Each of n rows needs n coefficients and one RHS'].
 (input allSatisfy: [:row | row allSatisfy: [:v |
  v isInteger or: [v isFraction]]])
  ifFalse: [Error signal: 'Use only Integer or Fraction entries'].
 matrix := input collect: [:row | row copy].
 solution := Array new: n. trace := OrderedCollection new.
 record := [:label | keepTrace ifTrue: [trace add:
  {label. matrix collect: [:row | row copy]. solution copy}]].
 record value: 'Initial augmented matrix'. nextRow := 1.
 1 to: n do: [:col |
  pivot := (nextRow to: n)
   detect: [:r | ((matrix at: r) at: col) ~= 0] ifNone: [0].
  pivot = 0
   ifTrue: [record value: 'No pivot in column ', col printString]
   ifFalse: [
    pivot ~= nextRow ifTrue: [
     temp := matrix at: nextRow.
     matrix at: nextRow put: (matrix at: pivot). matrix at: pivot put: temp.
     record value: 'Swap rows ', nextRow printString, ' and ', pivot printString].
    nextRow + 1 to: n do: [:r |
     factor := ((matrix at: r) at: col) / ((matrix at: nextRow) at: col).
     col to: n + 1 do: [:j | (matrix at: r) at: j put:
      (((matrix at: r) at: j) - (factor * ((matrix at: nextRow) at: j))) ]].
    record value: 'Pivot column ', col printString, '; zeros below row ', nextRow printString.
    nextRow := nextRow + 1]].
 status := (matrix anySatisfy: [:row |
  ((1 to: n) allSatisfy: [:j | (row at: j) = 0]) and: [row last ~= 0]])
   ifTrue: [#inconsistent]
   ifFalse: [nextRow = (n + 1) ifTrue: [#unique] ifFalse: [#underdetermined]].
 status = #unique
  ifTrue: [n to: 1 by: -1 do: [:i |
   rhs := (matrix at: i) last.
   i + 1 to: n do: [:j | rhs := rhs - (((matrix at: i) at: j) * (solution at: j))].
   solution at: i put: rhs / ((matrix at: i) at: i).
   record value: 'Back substitute x', i printString]]
  ifFalse: [solution := nil].
 {status. solution. matrix. trace asArray}].
dependent := solve value: #(#(1 2 3) #(2 4 6)) value: false.
impossible := solve value: #(#(1 2 3) #(2 4 7)) value: false.
skipped := solve value: #(#(0 1 2) #(0 2 4)) value: false.
{dependent first. impossible first. skipped first. dependent second}

Expected value: #(underdetermined inconsistent underdetermined nil)

Check: The skipped-column example needs a pivot in column 2 while nextRow is still 1. A missing diagonal alone does not prove inconsistency.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Tell no solution from more than one solution, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

08 · Check the answer against the original equations

For each original row, multiply its coefficients by the candidate solution, sum them, and subtract its RHS. This residual uses the untouched input, not the transformed matrix. With exact rational arithmetic every residual must equal the Integer zero.

Residual checking is a second view of the computation. It reuses the mathematical definition of a solution, but not the elimination transformations. If a coefficient or RHS were accidentally changed during row copying, checking only the transformed matrix could hide that defect. The untouched original is the appropriate reference.

Independent Workspace expression · select all, then Print it
| solve rows answer residuals |
solve := [:input :keepTrace |
 | n matrix solution trace record nextRow pivot temp factor status rhs |
 (input isArray and: [input notEmpty])
  ifFalse: [Error signal: 'Use a nonempty Array of augmented rows'].
 ((keepTrace == true) or: [keepTrace == false])
  ifFalse: [Error signal: 'The trace flag must be true or false'].
 n := input size.
 (input allSatisfy: [:row | row isArray and: [row size = (n + 1)]])
  ifFalse: [Error signal: 'Each of n rows needs n coefficients and one RHS'].
 (input allSatisfy: [:row | row allSatisfy: [:v |
  v isInteger or: [v isFraction]]])
  ifFalse: [Error signal: 'Use only Integer or Fraction entries'].
 matrix := input collect: [:row | row copy].
 solution := Array new: n. trace := OrderedCollection new.
 record := [:label | keepTrace ifTrue: [trace add:
  {label. matrix collect: [:row | row copy]. solution copy}]].
 record value: 'Initial augmented matrix'. nextRow := 1.
 1 to: n do: [:col |
  pivot := (nextRow to: n)
   detect: [:r | ((matrix at: r) at: col) ~= 0] ifNone: [0].
  pivot = 0
   ifTrue: [record value: 'No pivot in column ', col printString]
   ifFalse: [
    pivot ~= nextRow ifTrue: [
     temp := matrix at: nextRow.
     matrix at: nextRow put: (matrix at: pivot). matrix at: pivot put: temp.
     record value: 'Swap rows ', nextRow printString, ' and ', pivot printString].
    nextRow + 1 to: n do: [:r |
     factor := ((matrix at: r) at: col) / ((matrix at: nextRow) at: col).
     col to: n + 1 do: [:j | (matrix at: r) at: j put:
      (((matrix at: r) at: j) - (factor * ((matrix at: nextRow) at: j))) ]].
    record value: 'Pivot column ', col printString, '; zeros below row ', nextRow printString.
    nextRow := nextRow + 1]].
 status := (matrix anySatisfy: [:row |
  ((1 to: n) allSatisfy: [:j | (row at: j) = 0]) and: [row last ~= 0]])
   ifTrue: [#inconsistent]
   ifFalse: [nextRow = (n + 1) ifTrue: [#unique] ifFalse: [#underdetermined]].
 status = #unique
  ifTrue: [n to: 1 by: -1 do: [:i |
   rhs := (matrix at: i) last.
   i + 1 to: n do: [:j | rhs := rhs - (((matrix at: i) at: j) * (solution at: j))].
   solution at: i put: rhs / ((matrix at: i) at: i).
   record value: 'Back substitute x', i printString]]
  ifFalse: [solution := nil].
 {status. solution. matrix. trace asArray}].
rows := #(#(0 2 1 7) #(2 1 -1 1) #(1 -1 2 5)).
answer := (solve value: rows value: false) second.
residuals := rows collect: [:row | | sum |
 sum := 0.
 1 to: answer size do: [:j | sum := sum + ((row at: j) * (answer at: j))].
 sum - row last].
residuals

Expected value: #(0 0 0)

Check: A zero residual proves this candidate solves the equations. The full-pivot status is what additionally establishes uniqueness.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Check the answer against the original equations, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

09 · Keep snapshots instead of references to changing rows

Enable the trace to record the initial matrix, each row exchange, each completed pivot column and each back-substitution result. Each snapshot copies its rows and solution array. Without those copies, all frames could accidentally show the final state.

Each trace record has three slots: an operation label, copied augmented rows and a copied partial solution. The numeric entries themselves need no custom cloning: Integer and Fraction values are not modified in place by these arithmetic sends. A separate copy is necessary for each containing Array, because later at:put: messages replace its entries.

Independent Workspace expression · select all, then Print it
| solve result history |
solve := [:input :keepTrace |
 | n matrix solution trace record nextRow pivot temp factor status rhs |
 (input isArray and: [input notEmpty])
  ifFalse: [Error signal: 'Use a nonempty Array of augmented rows'].
 ((keepTrace == true) or: [keepTrace == false])
  ifFalse: [Error signal: 'The trace flag must be true or false'].
 n := input size.
 (input allSatisfy: [:row | row isArray and: [row size = (n + 1)]])
  ifFalse: [Error signal: 'Each of n rows needs n coefficients and one RHS'].
 (input allSatisfy: [:row | row allSatisfy: [:v |
  v isInteger or: [v isFraction]]])
  ifFalse: [Error signal: 'Use only Integer or Fraction entries'].
 matrix := input collect: [:row | row copy].
 solution := Array new: n. trace := OrderedCollection new.
 record := [:label | keepTrace ifTrue: [trace add:
  {label. matrix collect: [:row | row copy]. solution copy}]].
 record value: 'Initial augmented matrix'. nextRow := 1.
 1 to: n do: [:col |
  pivot := (nextRow to: n)
   detect: [:r | ((matrix at: r) at: col) ~= 0] ifNone: [0].
  pivot = 0
   ifTrue: [record value: 'No pivot in column ', col printString]
   ifFalse: [
    pivot ~= nextRow ifTrue: [
     temp := matrix at: nextRow.
     matrix at: nextRow put: (matrix at: pivot). matrix at: pivot put: temp.
     record value: 'Swap rows ', nextRow printString, ' and ', pivot printString].
    nextRow + 1 to: n do: [:r |
     factor := ((matrix at: r) at: col) / ((matrix at: nextRow) at: col).
     col to: n + 1 do: [:j | (matrix at: r) at: j put:
      (((matrix at: r) at: j) - (factor * ((matrix at: nextRow) at: j))) ]].
    record value: 'Pivot column ', col printString, '; zeros below row ', nextRow printString.
    nextRow := nextRow + 1]].
 status := (matrix anySatisfy: [:row |
  ((1 to: n) allSatisfy: [:j | (row at: j) = 0]) and: [row last ~= 0]])
   ifTrue: [#inconsistent]
   ifFalse: [nextRow = (n + 1) ifTrue: [#unique] ifFalse: [#underdetermined]].
 status = #unique
  ifTrue: [n to: 1 by: -1 do: [:i |
   rhs := (matrix at: i) last.
   i + 1 to: n do: [:j | rhs := rhs - (((matrix at: i) at: j) * (solution at: j))].
   solution at: i put: rhs / ((matrix at: i) at: i).
   record value: 'Back substitute x', i printString]]
  ifFalse: [solution := nil].
 {status. solution. matrix. trace asArray}].
result := solve value: #(#(0 2 1 7) #(2 1 -1 1) #(1 -1 2 5)) value: true.
history := result fourth.
{history size. (history at: 2) first. history last third}

Expected value: {8. 'Swap rows 1 and 2'. #(1 2 3)}

Check: The third pivot frame intentionally repeats the matrix: that column is already triangular. The following three frames reveal z, y, then x.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 9: Keep snapshots instead of references to changing rows, with its evaluated result
Actual Squeak 6.1 Workspace after Print it. The selected result was computed from the displayed complete expression.

Why these transformations are safe

The essential invariant is that every intermediate augmented matrix describes exactly the same solution set as the input. Swapping two whole rows only changes equation order. Replacing a lower row by itself minus a multiple of a different pivot row is reversible by adding that same multiple back. We never divide by a zero pivot: the search either finds a nonzero candidate or skips the column.

There is also a shape invariant. Before processing a new pivot row, entries below previous pivots are zero. The chosen candidate comes from those lower rows, so exchanging it upward does not disturb those earlier zeros. Subtracting its multiple from other lower rows also preserves them. Eliminating in the current column extends that zero pattern by one pivot.

All scans are bounded by the finite dimensions. Every column is visited once and nextRow increases only when a pivot exists. After forward elimination, a zero-coefficient row with nonzero RHS witnesses inconsistency. Otherwise fewer than n pivots leaves free variables. With n pivots the upper-triangular system has a nonzero diagonal, and the descending loop determines exactly one value at each step. Residual tests confirm particular executions; these invariants explain the general algorithm.

Count arithmetic separately from integer size

For a dense n × n coefficient matrix, the forward phase has a column loop, a lower-row loop and an entry loop. Its arithmetic-operation count is O(n³); back substitution is O(n²). Searching for the first nonzero pivot adds at most O(n²) coefficient checks. The input validation and working-row copy are also O(n²). These are asymptotic counts for this implementation, not benchmark measurements.

With tracing off, the working matrix uses O(n²) numeric slots plus O(n) solution slots. With tracing on, there are O(n) full snapshots: one per column, up to one row exchange per column, and one per solved variable. Since each matrix snapshot copies O(n²) slots, the teaching trace retains O(n³) slots. It also adds O(n³) copying work. Tracing only once per pivot column, rather than once per individual row update, keeps the number of snapshots linear.

Exact rational operations are not constant-time machine instructions. Numerators and denominators can grow, and their arithmetic and reduction cost depends on the number of digits. The complexity bounds above count operations and stored references, not seconds or bytes. Exactness prevents rounding drift; it does not make huge rational systems cheap. Use small systems here, and use a measurement workflow before making any speed claim.

Verify the contract, not just the demonstration

The downloaded assertion expression returns 2757 in native Squeak 6.1 build 23976. It signals an Error on the first failed check. These are direct assertions, not a claimed SUnit suite. The verification log records all nine published checkpoints plus the complete assertion total.

  • 9 checkpoint assertions: evaluate the exact source displayed on this page.
  • 2619 assertions across 729 complete 2 × 2 systems: every coefficient and RHS comes from −1, 0 or 1. An independent determinant/Cramer formula classifies each system and checks unique answers. Every case checks input preservation; unique cases also check exact residuals, and nonunique cases check nil.
  • 100 assertions across 25 constructed systems: dimensions 1 through 5, known rational solutions and reversed endpoint rows exercise larger systems and row exchange.
  • 13 rejection checks: malformed arrays, empty input, Float, nil, text and Boolean entries, plus four invalid trace flags.
  • 8 explicit edge checks: two required row swaps, a completely zero 3 × 3 system, one-equation cases, skipped pivot columns and an exact answer with denominator 1050.
  • 8 trace and ownership checks: initial and final snapshots, partial solution entries, independent row/solution copies and trace-off behavior.

The 2 × 2 oracle does not implement elimination, so it is unlikely to repeat a row-update bug. The larger cases construct a triangular matrix with nonzero diagonal, choose the answer first, calculate its RHS, and exchange rows before solving. This is reproducible evidence, not random lucky examples or a proof over all possible inputs.

To reproduce the result, open the test file as text, select its complete expression and Print it. Use a copy of your learning image if experimenting. The release captures were generated in a disposable image/changes copy and quit without saving. All eight visual states were also evaluated in that native image.

When an answer looks wrong

The first division fails
Check that the pivot search ran before division and that row zero was never indexed. Swapping the full row must include the RHS.
An odd-looking Fraction appears
That is often the correct intermediate state. The third-row values −3/2, 5/2 and 9/2 are expected after the first pivot. Do not round them or replace / with //.
A singular system is reported as unique
Check the number of accepted pivots, not merely the number of loop iterations. A skipped column does not advance nextRow.
Every replay frame shows the final matrix
Copy each row when recording a snapshot, not just the outer matrix. Copy the partial solution Array too.
The compiler says a name is already used
Keep each checkpoint independent. Squeak rejects a block argument or local temporary that shadows a name in its enclosing expression. When extending the snippet, choose fresh outer names rather than redeclaring the solver’s inner names.

Exercises that preserve an explicit contract

  1. One equation, three outcomes. Predict the status and solution slot for rows #(3 2), #(0 0) and #(0 2). Run them using the complete solver checkpoint. Explain why only the first has a unique answer.
  2. Audit the row operation. Add a test that substitutes #(1 2 3) into every recorded matrix. Every row’s residual should still be zero, including the RHS after the swap. Keep the original residual test too.
  3. Expose rank. Add rank = nextRow − 1 as a fifth result field. Preserve the existing four slots and update the test contract. Compare rank for a full-rank system, duplicate rows and an all-zero matrix.
  4. Return a family, not a guess. For consistent singular systems, identify free columns and express pivot variables in terms of parameters. Begin with x + 2y = 3. This extends the contract; do not call the old nil marker an error.
  5. Move into objects. Extract the solver into a class-side method and translate the direct assertions into SUnit. Keep the exact-domain validation, source preservation and independent oracle rather than testing only the visible example.

For related exact state updates, continue with Euclid’s algorithm or Horner polynomial evaluation. They use the same Smalltalk numeric objects, but preserve different invariants.

Sources and scope

NIST Digital Library of Mathematical Functions, §3.2(i) describes augmented-matrix elimination, back substitution and partial pivoting. Per-Olof Persson’s UC Berkeley Math 128A notes, chapter 6 present elementary row operations, row exchange and arithmetic-operation counts. Both were reviewed 29 October 2026. These references describe the underlying method; the checked Smalltalk implementation, examples, independent test grid and native trace are original to this lesson.

The official Squeak documentation is the environment reference. Integer/Fraction arithmetic, Array copying, Workspace Print it and Morphic imageForm were verified directly in the supplied Squeak 6.1 image. This is an exact educational solver for small square systems, not a general numerical linear-algebra package.