Jump to content

Ordinary derivative/Practice/Calculation and plotting with Python: Difference between revisions

From Wikibase
No edit summary
No edit summary
Line 310: Line 310:


[[File:Cubic polynomial with its numerical derivatives.png|thumb|alt=Three panels: the cubic curve; its first derivative with four numerical versions falling on the exact parabola; its second derivative as a straight line with a spurious drop at both ends|Left: $f$ on $[-2.8,2.8]$. Middle: the first derivative by four methods against $f'$. Right: the second derivative against $f''$, where the double <code>np.gradient</code> breaks down at both ends.]]
[[File:Cubic polynomial with its numerical derivatives.png|thumb|alt=Three panels: the cubic curve; its first derivative with four numerical versions falling on the exact parabola; its second derivative as a straight line with a spurious drop at both ends|Left: $f$ on $[-2.8,2.8]$. Middle: the first derivative by four methods against $f'$. Right: the second derivative against $f''$, where the double <code>np.gradient</code> breaks down at both ends.]]
<!-- why np.gradient breaks down? Fix it! -->
{{End hidden}}
{{End hidden}}



Revision as of 05:05, 20 November 2026

Languages: English · français · Esperanto

Reference: Formal definition

The four 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 Matplotlib.

Exercise 1

Plot, on the same graph, with legends, a title, and symbols, the two Gaussian functions on $[-3,3]$:

$$ y_1(x)=\frac{\exp\left(-0.25x^{2}\right)}{\sqrt{2\pi}} $$

$$ y_2(x)=\frac{\exp\left(-0.5x^{2}\right)}{\sqrt{2\pi}} $$

Exercise 2

Plot, on the same graph, with legends, a title, and symbols, the four functions:

  1. (a) $\exp(-0.5x^{2})/\sqrt{2\pi}$
  2. (b) $\sin(x)$
  3. (c) $\cos(x)$
  4. (d) $|x|$

Exercise 3

Determine numerically the derivative of $\sin(x)$ for the steps $h=0.5$, $h=0.1$, and $h=0.01$, then compare the errors with the exact solution $\cos(x)$.

Reminder, from the definition of the derivative:

$$ \frac{df}{dx}=f'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}{h} $$

The limit is approximated by a finite $h\ll1$, which may be taken forward, backward, or centred:

$$ \begin{cases} f'(x)\approx\dfrac{f(x+h)-f(x)}{h} \\ f'(x)\approx\dfrac{f(x)-f(x-h)}{h} \\ f'(x)\approx\dfrac{f(x+h)-f(x-h)}{2h} \end{cases} $$

Exercise 4

Let $f$ be the function

$$ f(x)=2x^{3}+4x^{2}-3x+1 $$

for $-2.8\le x\le2.8$. Write a script that:

  1. builds the vectors $X$ and $Y$ holding $x$ and $y=f(x)$ with a step $h=0.1$;
  2. plots the curve $y=f(x)$ from $X$ and $Y$;
  3. computes numerically, by several methods, the first derivative of $f$;
  4. computes numerically, by several methods, the second derivative of $f$;
  5. plots, on one graph, the first derivatives of 3 against the exact first derivative;
  6. plots, on one graph, the second derivatives of 4 against the exact second derivative.

References