In [26]:
# this line is needed for the web notebook only
%matplotlib inline
CIVL4250 Numerical Methods in Engineering
Dr Dorival Pedroso
Code available on https://github.com/cpmech/CIVL4250py
See, e.g. Wikipedia
Starting with the three numbers: 0, 1, 1, the Fibonacci sequence can be constructed in such a way the new number is a sum of the previous two. Mathematically, if the new number is $F_k$, then:
$F_k = F_{k-2} + F_{k-1}$
These numbers can be easily generated in Python; however we will ignore the first zero number for the sake of convenience at the moment. First, let's create the initial list
In [27]:
x = [1, 1]
The number of Fibonnaci numbers, except the first three, will be
In [28]:
n = 21
The two previous numbers in x can be accessed as follows
In [29]:
last_but_one = x[-1] # also "penultimate", "second to last", "next to last"
last_but_two = x[-2] # also "antepenultimate", "two before the last"
print 'last but one =', last_but_one
print 'last but two =', last_but_two
Now, the sequence can be easily generated by appending the addition of the two last numbers, successively
In [30]:
print 'x (before) =', x
for i in range(n):
x.append(x[-2] + x[-1])
print 'x (after) =', x
By dividing each Fibonacci number by its predecessor, the results converge to a nice number, the golden ratio given by $\frac{1 + \sqrt{5}}{2}$.
In our code, the easiest way to verify this is to first convert the x
list into a proper vector (array of real numbers). This can be accomplished by using array
from numpy
.
The array
function gets x
and a flag such as dtype=float
as input. The flag tells array
to convert integers to floats. The following code is then written
In [31]:
import numpy as np
x = np.array(x, dtype=float)
print 'x (vector) =', x
All numbers after the first one in x
and up to the end of the sequence can be recovered by using the slice notation. This is achieved as follows
In [32]:
x_upper = x[1:]
print 'x_upper =', x_upper
Similarly, all numbers from the beginning of the sequence up to the last but one are obtained by means of
In [33]:
x_lower = x[:-1]
print 'x_lower =', x_lower
Now, we can divide each component of one array by the corresponding one in the other array with the following code
In [34]:
g = x_upper / x_lower
print 'g =', g
These results can be plotted in order to visualise the convergence towards the golden ratio
In [35]:
import matplotlib.pyplot as plt
plt.plot(g);