The expression is the Binet formula for the Fibonacci numbers. Compute the two roots and round the result to the nearest integer:
from math import sqrt


def binet(n):
    phi = (1 + sqrt(5)) / 2
    psi = (1 - sqrt(5)) / 2
    return round((phi**n - psi**n) / sqrt(5))
The returned object is an integer. This floating-point arithmetic implementation correctly rounds the requested range through ; it is not an arbitrary-precision method for indefinitely large . An integer recurrence is a useful independent numerical check.
A list comprehension evaluates the function for the fifty required indices:
list50 = [binet(n) for n in range(1, 51)]
Python's upper range endpoint is excluded, so 51 includes index 50. The first entries are , and the final entry is .
Use the first 10, 20, 30 and 40 entries of the already computed list in a two-by-two array of axes. Each subplot needs an index sequence starting at one and having the same length as its data:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2, figsize=(8, 6), layout="constrained")
for ax, stop in zip(axes.flat, [10, 20, 30, 40]):
    ax.plot(range(1, stop + 1), list50[:stop])
    ax.set(title=f"n = {stop}", xlabel="n", ylabel="f(n)")
plt.show()
The panels use different vertical scales, which is why the exponential-looking growth remains visible at each range. The available values through 50 are retained in list50, even though the requested four panels stop at 40.
Figure 1.
Fibonacci growth over four index ranges, generated directly from the closed formula
. Details.

Articles by others on the same topic (0)

There are currently no matching articles.