Jump to content

Function/Practice/Functions with Python

From Wikibase
Revision as of 10:26, 20 November 2026 by Rongzhou (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Languages: English · français · Esperanto

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

  1. What does max(2, 3) return?
  2. 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.

Exercise 2

  1. Build a square $3\times3$ matrix of integers of your choice, named $A$.
  2. Test the commands np.trace(A) and np.sum(diag(A)) from numpy
  3. 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}. $$

Exercise 3

Plot the following parametric curves.

1. A Lissajous curve,

$$ \begin{cases} x(t)=\sin(2t) \\ y(t)=\sin(3t) \end{cases},\,-2\pi\le t\le2\pi $$

2. The same pair of sines, with a linear drift,

$$ \begin{cases} x(t)=t+\sin(2t) \\ y(t)=t+\sin(3t) \end{cases},\,-4\pi\le t\le4\pi $$

3. A curve in 3D Euclidean space,

$$ \begin{cases} x(t)=t\cos(t) \\ y(t)=t\sin(t) \\ z(t)=t \end{cases},\,-2\pi\le t\le2\pi $$

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.

1. The equation satisfied by the golden ratio

Show that $\varphi$ satisfies

$$ \varphi^{2}-\varphi-1=0. $$

2. A function for the quadratic equation

Write a function quadratic_solve(a, b, c) that gives the solutions of

$$ ax^{2}+bx+c=0. $$

3. The value of the golden ratio

Prove that

$$ \varphi=\frac{1+\sqrt{5}}{2}\approx1.618. $$

4. The Fibonacci sequence

Let $F_n$ be the Fibonacci sequence defined by

$$ F_{n+2}=F_{n+1}+F_n $$

with $F_1=F_2=1$. Write a program that gives the terms of the sequence up to a rank $N$, set at the beginning of the program, i.e., $N=20$.

5. Numerical convergence of the ratios

Verify numerically that the ratio $\dfrac{F_{n+1}}{F_n}$ tends to the golden ratio.

6. The golden spiral

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$.

References