The five exercises below come from a practical-work handout written for Matlab created by my beloved teacher M. Gautier List[1], which we solve here with NumPy and SymPy.
Exercise 1
What does max(2, 3) return?
Write a function $m=\mathrm{mymax}(a,b,c)$ that returns the maximum of a set of n numbers $\max \{x_1,\dots,x_n\}$, without using the function max.
Question 1.
print(max(2,3))
Expected output:
3
In Python max accepts either several arguments (max(1, 2, 3, 4)) or one iterable (max([2, 3, 4, 6]))
Question 2/3.
test_list=[1,2,3,4,5,6]defmymax(number_list:list[int])->int:# do not name number_list "list": overshadowing Python built-in keywords breaks code unpredicatably and make you an unhappy individualmaximum=number_list[0]# initialize from the first element so comparison works; again do not name maximum "max".fornumberinnumber_list[1:]:ifnumber>maximum:maximum=numberreturnmaximumprint(f"test list max: {mymax(test_list)}")
Expected output:
test list max: 6
Caution:
Assignment: =
Commparison: ==
Writing if a = b: buys a syntax error in Python, and if a == b: where a is supposed to be assigned to b causes a silent logic error: the assignment is not made, but Python doesn't complain.
Exercise 2
Build a square $3\times3$ matrix of integers of your choice, named $A$.
Test the commands np.trace(A) and np.sum(diag(A)) from numpy
Write a function $t=\mathrm{mytrace}(A)$ that computes the trace of any matrix, without using the functions trace, sum, or diag.
Recall that the trace of a square matrix $A=(a_{ij})$ is the sum of its diagonal entries,
$$
\operatorname{tr}(A)=\sum_{i=1}^{n}a_{ii}.
$$
Questions 1 and 2.np.trace computes the trace directly, while np.sum(np.diag(A)) extracts the diagonal with np.diag and then sums it: two routes to the same number.
Question 3. Walk down the diagonal with a single index and accumulate the entries in a variable initialised at $0$.
defmytrace(A):"""Trace of a square matrix, without numpy's trace(), sum(), or diag()."""n=len(A)ifany(len(row)!=nforrowinA):raiseValueError(f"mytrace handles only square matrixs of dimension n*n;{A} is not a square matrix")t=0foriinrange(n):t+=A[i][i]# A[i][i] on a list of lists, or on an arrayreturntprint(mytrace([[1,2,3],[4,5,6],[7,8,9]]))try:mytrace([[1,2,3],[4,5,6]])exceptValueErroraserr:print("not square ->",err)
Expected output:
15
not square -> mytrace handles only square matrixs of dimension n*n;[[1, 2, 3], [4, 5, 6]] is not a square matrix
np.diag is versatile:
on a 2D array it extracts the diagonal;
on an 1D array it does the opposite and builds a diagonal matrix.
importnumpyasnpimportmatplotlib.pyplotaspltfig=plt.figure(figsize=(13,4.2))# 1. the Lissajous curvet=np.linspace(-2*np.pi,2*np.pi,601)ax=fig.add_subplot(1,3,1)# set plot target (ax) to plot 1 of a plot panel with 1 row and 3 columns (fig), ax.plot(np.sin(2*t),np.sin(3*t),lw=1.2)ax.set_aspect("equal")# same scale on both axes: a circle stays roundax.set_title(r"$x=\sin(2t)$, $y=\sin(3t)$")ax.set_xlabel("$x(t)$")ax.set_ylabel("$y(t)$")ax.grid(alpha=0.3)# semi-transparent gridlines# 2. the same, with a linear driftt=np.linspace(-4*np.pi,4*np.pi,1201)ax=fig.add_subplot(1,3,2)ax.plot(t+np.sin(2*t),t+np.sin(3*t),lw=1.2)ax.set_aspect("equal")ax.set_title(r"$x=t+\sin(2t)$, $y=t+\sin(3t)$")ax.set_xlabel("$x(t)$")ax.set_ylabel("$y(t)$")ax.grid(alpha=0.3)# 3. a curve in spacet=np.linspace(-2*np.pi,2*np.pi,601)ax=fig.add_subplot(1,3,3,projection="3d")# plot handles 3D just like 2D once you specify projection="3d"ax.plot(t*np.cos(t),t*np.sin(t),t,lw=1.2)ax.set_title(r"$x=t\cos t$, $y=t\sin t$, $z=t$")ax.set_xlabel("$x$")ax.set_ylabel("$y$")ax.set_zlabel("$z$")fig.tight_layout()plt.show()
Left: the Lissajous curve (Q1). Middle: a diagonal drift decorated with loops (Q2) Right: the spatial curve (Q3), a corkscrew whose radius grows with $t$.
Notice the periods for curve 1&2: $x$ has period $\pi$ and $y$ has period $2\pi/3$, so their common period is $2\pi$, and the interval $-2\pi\le t\le2\pi$ consists of two periods.
Without set_aspect("equal") the figure is stretched by the shape of the axes, and curves look distorted.
The third curve has radius $\sqrt{x^{2}+y^{2}}=|t|$ which grows with $|t|$, drawing a corkscrew opening outwards.
Exercise 3: the golden ratio and the Fibonacci sequence
The golden ratio is a proportion originally defined in geometry as the ratio of 2 lengths $a$ and $b$, noted $\varphi$, such that
$$
\varphi=\frac{a}{b}=\frac{a+b}{a}
$$
with $a>b>0$. Said ratio appears not only in human-creations (paintings, sculptures, architecture, etc.), but also in nature.
importcmathdefquadratic_solve(a,b,c):"""Return the two roots of a*x**2 + b*x + c = 0."""ifa==0:raiseValueError("a is zero: this is not a second-degree equation")delta=b*b-4*a*c# the discriminantdelta_root=cmath.sqrt(delta)# cmath.sqrt handles square root with complex numbers, so this covers delta < 0 as wellreturn(-b+delta_root)/(2*a),(-b-delta_root)/(2*a)# testfora,b,cin[(1,-1,-1),(1,-3,2),(1,0,1),(2,4,2)]:print(f"a={a}, b={b}, c={c} -> {quadratic_solve(a,b,c)}")
Note cmath.sqrt always returns a complex number, so our quadratic_solve function does as well. When the imaginary part 0j, the root is acutally real.$:
By convention, on takes the positive value $\varphi=\frac{1+\sqrt{5}}{2}$.
Alternatively, we can also be lazy and solve (1) with the quadratic_solve function we just handrolled.
Or with Sympy:
importsympyasspx=sp.symbols("x")roots=sp.solve(x**2-x-1,x)# x**2 - x - 1 = 0print("roots:",roots)phi=max(roots,key=lambdar:float(r))# Pick the positive root, notice since roots are sympy objects, direct comparison does not work without float conversion.print("Phi:",phi)print(f"Phi (approximate): {float(phi):.3f}")
Python integers have no fixed upper limit, so the iterative loop can run to $N=1000$ and beyond (warning: it will take a while). The terms are automatically converted to a float approximation above $1.8\cdot10^{308}$, which happens for $F_n$ at $n=1477$.
5. Numerical convergence of the ratios
Verify numerically that the ratio $\dfrac{F_{n+1}}{F_n}$ tends to the golden ratio.
importnumpyasnpphi=(1+np.sqrt(5))/2print(f"{'n':>3}{'F_{n+1}/F_n':>16}{'|error|':>10}")forninrange(1,N):r=F[n]/F[n-1]# F_{n+1} / F_nerr=abs(r-phi)print(f"{n:3d}{r:16.12f}{err:10.2e}")# 16.12f: minimum width 16, 12 digits after decimal point, fixed-point notation (f). 10.2e: exponential notation (e)
As seen, the error decreases as $n$ increases, demonstrating convergence.
Left: the ratio $F_{n+1}/F_n$ against $\varphi$. Right: the absolute error $|F_{n+1}/F_n-\varphi|$ on a logarithmic scale, which interestingly follow the line $\sqrt{5}\,\varphi^{-2n}$. (Illustration, not an output of the script above)
The golden spiral, built on the proportions of the golden ratio, can be drawn as the polar equation
$$
r(\theta)=A\varphi^{2\theta/\pi}
$$
where $A$ is the scale factor.
Plot the golden spiral choosing an arbitrary value for $A$.
$A$ is only a scale: it does not change the shape of the spiral, so choose the simplest choice $A=1$.
importnumpyasnpimportmatplotlib.pyplotaspltphi=(1+np.sqrt(5))/2theta=np.linspace(0,6*np.pi,1000)r=phi**(2*theta/np.pi)# A = 1fig=plt.figure(figsize=(5,5))ax=fig.add_subplot(projection="polar")# or plt.subplots(subplot_kw={"projection": "polar"})ax.plot(theta,r,color="goldenrod",lw=2)ax.set_rlim(0,r.max())ax.set_rticks([5,25,100])ax.set_rlabel_position(67.5)# where the r labels sit, in degreesplt.show()
The golden spiral for $A=1$ and $0\le\theta\le4\pi$