Illustration for “Matrix multiplication for Fibonacci” (1 of 2)

When you have four sections in an RC phase-shift circuit, it is quite a mundane task to write down Kirchhoff's equations and to solve them. Calculation of the complex voltage transfer function can easily fill about four A4 pages. In this situation, matrix algebra can give you a great boost. Your vector is (UiIi)\begin{pmatrix} U_i \\ I_i \end{pmatrix}at the input of a circuit; a matrix transforms it into (UoIo)\begin{pmatrix} U_o \\ I_o \end{pmatrix} at the output of the circuit. It's a game changer because instead of a set of equations you can now reason about operations and their properties (hello, group theory!). Four identical RC stages become M raised to the power of 4 and, when you know what you're doing, this trick simplifies calculations to almost as simple as "write down the answer".

In order to use this power, we need to decide what our state vector is. In electronics it's the vector (UI)\begin{pmatrix} U \\ I \end{pmatrix}; for Fibonacci numbers it's the vector (ab)\begin{pmatrix} a \\ b \end{pmatrix} of two consecutive numbers. Let's check our assignment which moves us one position to the right:

a, b = b, a + b

Illustration for “Matrix multiplication for Fibonacci” (2 of 2)

Now one can derive the matrix for one jump:

M=(0111).M = \begin{pmatrix} 0 & 1 \\ 1 & 1 \end{pmatrix}.

Now the idea already stated by one of our subscribers, is quite clear. Power of one step matrix allows to perform a required number of steps.

Mn(01)=(FnFn+1),M^n\begin{pmatrix}0\\1\end{pmatrix} =\begin{pmatrix}F_n\\F_{n+1}\end{pmatrix},

Therefore, if we can quickly calculate the power of matrix, we can quickly calculate required element of the Fibonacci sequence. Lucky us. We just learned how to perform this task.

pub fn fib(mut n: i32) -> i32 {
  let (mut xa, mut xb, mut xc, mut xd) = (0, 1, 1, 1);
  let (mut ka, mut kb, mut kc, mut kd) = (0, 1, 1, 1);

  while n > 0 {
    if n % 2 == 1 {
      (xa, xb, xc, xd) = (
        xa * ka + xb * kc,
        xa * kb + xb * kd,
        xc * ka + xd * kc,
        xc * kb + xd * kd,
      );
    }

    (ka, kb, kc, kd) = (
      ka * ka + kb * kc,
      ka * kb + kb * kd,
      kc * ka + kd * kc,
      kc * kb + kd * kd,
    );

    n = n / 2;
  }

  xa
}

The full solution on github