Using matrix multiplication to calculate Fibonacci numbers
In this post, we will discuss how to calculate the Fibonacci number using matrix multiplication. To skip straight to the code, click here.
Matrix Multiplication
This algorithm involves multiplying 2x2
matrices together, more specifically this matrix…
For a reminder on how to multiply matrices, view this article on mathsisfun.
Using the matrix
The matrix above can be used to calculate the Fibonacci number. By raising the matrix to the power of , we can get the Fibonacci number.
The result of the matrix multiplication will be a matrix with the fibonacci number in the top left corner.
Example
To find the number in the sequence, we raise the matrix to the power 5…
and we look at the number in the top left corner of the resulting matrix.
Therefore, the number in the sequence is 8
Speeding up with fast exponents
We can use a simple maths trick to speed up raising our matrix to large powers. Consider the following examples…
From this we see that can be calculated by squaring and can be calculated by simply multiplying by 2.
Although this seems trivial, it can be used to calculate very quickly by simply breaking down the power into smaller powers.
We can generalise this formula …
Example
To get the number in the sequence…
As we can see, we can calculate the number in the sequence by breaking it down into smaller powers and multiplying them together. This problem is well suited to recursion, as gets larger, the number of computations increases at a rate of
Code
import numpy as np
def matrix_power(M, n):
"""
When we want to raise a matrix M to the power of n
we can use simply matrix multiplication, i.e multiply the matrix n times
"""
# If n is simply 1, then just return the matrix
if n == 1:
return M
# If n is even
elif n % 2 == 0:
# Call recursively with the product of multiplying the matrix by itself, but half the exponent each time
return matrix_power(np.dot(M, M), n // 2)
# If n is odd
else:
# We simply multiply m by the recursive call from the previous value of n
return np.dot(M, matrix_power(np.dot(M, M), (n - 1) // 2))
def fib_solution_5(n):
"""
This solution will use matrix multiplication to find the nth
fibonacci number
To find the nth fib number using matrix multiplication, we can multiply the following matrix by n-1...
------
1 1
1 0
------
The index [0,0] of this matrix will be the value of the nth fibonacci number
"""
if n <= 1:
return n
# Create our matrix to begin multiplication
m = np.array([[1, 1], [1, 0]])
# Raise our matrix to the power n and use our optimised function to do it efficiently
# Then simply extract the answer from the matrix in cell [
return matrix_power(m, n - 1)[0, 0]