Time for action – computing Fibonacci numbers

A matrix can represent the Fibonacci recurrence relation. We can express the calculation of Fibonacci numbers as a repeated matrix multiplication:

  1. Create the Fibonacci matrix as follows:
    F = np.matrix([[1, 1], [1, 0]])
    print("F", F)

    The Fibonacci matrix appears as follows:

    F [[1 1]
      [1 0]]
    
  2. Calculate the 8th Fibonacci number (ignoring 0), by subtracting 1 from 8 and taking the power of the matrix. The Fibonacci number then appears on the diagonal:
    print("8th Fibonacci", (F ** 7)[0, 0])

    The Fibonacci number is as follows:

    8th Fibonacci 21
    
  3. The golden ratio formula, better known as Binet's formula, allows us to calculate Fibonacci numbers with a rounding step at the end. Calculate the first eight Fibonacci ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.