Guess, Correct, Repeat

Systems of Linear EquationsMedium+20 XP+20

Guess, Correct, Repeat

Elimination solves Ax=bA\mathbf{x} = \mathbf{b}Ax=b in one pass. A different family of solvers never eliminates anything: it starts from a guess and improves it, again and again, until the guess stops changing. Each improvement is cheap, which is why large solvers often work this way.

The idea is to rearrange each equation so that one unknown stands alone. Equation iii,

ai0x0+ai1x1+⋯+ai,n−1xn−1=bi,a_{i0}x_0 + a_{i1}x_1 + \dots + a_{i,n-1}x_{n-1} = b_i,ai0​x0​+ai1​x1​+⋯+ai,n−1​xn−1​=bi​,

becomes

xi=bi−∑j≠iaij xjaiix_i = \frac{b_i - \sum_{j \ne i} a_{ij}\,x_j}{a_{ii}}xi​=aii​bi​−∑j=i​aij​xj​​

If you knew every other unknown, this would hand you xix_ixi​ exactly. You don't, so you plug in your current guess for them and get a better value for xix_ixi​. Doing that once for every unknown, in the order x0,x1,…,xn−1x_0, x_1, \dots, x_{n-1}x0​,x1​,…,xn−1​, is one sweep.

There are two classic ways to run a sweep. They differ in just one thing: where the values of the other unknowns come from.

methodwhen computing xix_ixi​, the other unknowns are taken from…
Jacobithe guess as it stood at the start of this sweep. New values only take over once the sweep is finished.
Gauss–Seidelthe latest values. Any xjx_jxj​ already updated earlier in this sweep is used straight away.

For example, take 4x0+x1=94x_0 + x_1 = 94x0​+x1​=9 and 2x0+5x1=92x_0 + 5x_1 = 92x0​+5x1​=9 with the starting guess (0,0)(0, 0)(0,0). Both methods begin with x0=9/4=2.25x_0 = 9/4 = 2.25x0​=9/4=2.25. Jacobi then computes x1=(9−2⋅0)/5=1.8x_1 = (9 - 2 \cdot 0)/5 = 1.8x1​=(9−2⋅0)/5=1.8 from the old x0x_0x0​, while Gauss–Seidel computes x1=(9−2⋅2.25)/5=0.9x_1 = (9 - 2 \cdot 2.25)/5 = 0.9x1​=(9−2⋅2.25)/5=0.9 from the new one.

Task: write sweep_solve(A, b, x0, sweeps, method).

  • A is an n×nn \times nn×n list of lists, and b and x0 are lists of length nnn. x0 is the starting guess.
  • Perform exactly sweeps sweeps (possibly 0) with method, which is either "jacobi" or "gauss-seidel".
  • Return the final guess as a list of floats, each rounded to 4 decimal places. With sweeps = 0 that is just x0, as floats.

Every diagonal entry aiia_{ii}aii​ in the tests is non-zero, and every test system is one where both methods close in on the true solution.

Examples

A = [[5, 2], [1, 4]]
b = [12, 10]
x0 = [0, 0]
sweeps = 2
method = "jacobi"
returns [1.4, 1.9]
A = [[5, 2], [1, 4]]
b = [12, 10]
x0 = [0, 0]
sweeps = 2
method = "gauss-seidel"
returns [1.64, 2.09]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run