Jump to content

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

From Wikibase
No edit summary
Exercise 3: grids built with np.linspace(retstep=True) instead of np.arange, imports moved to the top, both panels drawn from an explicit h = 0.5 grid, error orders stated in the conclusion. AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server)
Line 108: Line 108:


{{Hidden solution}}
{{Hidden solution}}
The three grids are built with <code>np.linspace(-2, 2, n, retstep=True)</code>: the number of points is fixed, and the call returns the step <code>dx</code> that the grid really has, which is the step the quotients divide by. <code>np.arange</code> gives no such guarantee, since its last point depends on how the round-off of the successive additions accumulates, so the end point has to be tested and patched.


<syntaxhighlight lang="python" class="pyodide" copy>
<syntaxhighlight lang="python" class="pyodide" copy>
h = 0.5                                          # modify for different precisions
x = np.arange(-2, 2 + h/2, h)
s = np.sin(x)
xx = np.linspace(-2, 2, 400)
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt


def forward(f, h):
def forward(f, h):
     return (f[1:] - f[:-1]) / h                  # approximation of derivative of x_i
     return (f[1:] - f[:-1]) / h                  # approximation of the derivative at x_i


def backward(f, h):
def backward(f, h):
     return (f[1:] - f[:-1]) / h                  # same slopes, but considered approximation of derivative of x_{i+1}
     return (f[1:] - f[:-1]) / h                  # same slopes, read as the derivative at x_{i+1}


def centred(f, h):
def centred(f, h):
     return (f[2:] - f[:-2]) / (2 * h)            # interior points only
     return (f[2:] - f[:-2]) / (2 * h)            # interior points only


# 1. the three steps of the question
steps = [0.5, 0.1, 0.01]
steps = [0.5, 0.1, 0.01]
err_forward, err_centred = [], []
err_forward, err_centred = [], []


for h in steps:
for h in steps:
     x = np.arange(-2, 2 + h/2, h)               # + h/2 keeps x = 2 on the grid
    n = int(round(4 / h)) + 1                    # 9, 41, and 401 points on [-2, 2]
     x, dx = np.linspace(-2, 2, n, retstep=True) # dx: the step the grid really has
     s = np.sin(x)
     s = np.sin(x)


     e_fwd = np.max(np.abs(forward(s, h) - np.cos(x[:-1])))
     e_fwd = np.max(np.abs(forward(s, dx) - np.cos(x[:-1])))
     e_bwd = np.max(np.abs(backward(s, h) - np.cos(x[1:])))
     e_bwd = np.max(np.abs(backward(s, dx) - np.cos(x[1:])))
     e_cen = np.max(np.abs(centred(s, h) - np.cos(x[1:-1])))
     e_cen = np.max(np.abs(centred(s, dx) - np.cos(x[1:-1])))


     err_forward.append(e_fwd)
     err_forward.append(e_fwd)
     err_centred.append(e_cen)
     err_centred.append(e_cen)
     print(f"h = {h:<5} n = {x.size:<4} max|err| forward {e_fwd:.3e}  backward {e_bwd:.3e}  centred {e_cen:.3e}")
     print(f"h = {dx:<5} n = {x.size:<4} max|err| forward {e_fwd:.3e}  backward {e_bwd:.3e}  centred {e_cen:.3e}")
 
# 2. the two panels: the quotients on the coarse grid, then the error against the step
x, h = np.linspace(-2, 2, 9, retstep=True)      # 9 points, so h = 0.5
s = np.sin(x)
xx = np.linspace(-2, 2, 400)


fig, ax = plt.subplots(1, 2, figsize=(10.5, 3.8))
fig, ax = plt.subplots(1, 2, figsize=(10.5, 4.0))


ax[0].plot(xx, np.cos(xx), "-", color="black", label=r"exact $\cos x$")
ax[0].plot(xx, np.cos(xx), "-", color="black", label=r"exact $\cos x$")
Line 149: Line 153:
ax[0].set_xlabel("$x$")
ax[0].set_xlabel("$x$")
ax[0].set_ylabel(r"$f'(x)$")
ax[0].set_ylabel(r"$f'(x)$")
ax[0].set_title(r"Derivative of $\sin x$ from the grid values")
ax[0].set_title(r"Derivative of $\sin x$ from the grid, $h=0.5$")
ax[0].grid(alpha=0.3)
ax[0].grid(alpha=0.3)
ax[0].legend()
ax[0].legend()
Line 159: Line 163:
ax[1].set_xlabel("$h$")
ax[1].set_xlabel("$h$")
ax[1].set_ylabel("max|err|")
ax[1].set_ylabel("max|err|")
ax[1].set_title("Error against the step")
ax[1].set_title("Maximum absolute error against the step")
ax[1].grid(alpha=0.3, which="both")
ax[1].grid(alpha=0.3, which="both")
ax[1].legend()
ax[1].legend()
Line 175: Line 179:
</pre>
</pre>


[[File:Numerical derivative of sine for three steps.png|thumb|alt=Left panel: markers of the forward difference around the exact cosine curve. Right panel: two straight lines on logarithmic axes, the centred one steeper|Left: the three quotients at $h=0.5$ against $\cos(x)$. Right: the maximum error against $h$, on logarithmic axes.]]
[[File:Numerical derivative of sine for three steps.png|thumb|alt=Left panel: markers of the forward and centred differences about the exact cosine curve at the 9 points of the coarse grid. Right panel: two straight lines on logarithmic axes, the centred one steeper|Left: the quotients at $h=0.5$ against $\cos(x)$. Right: the maximum error against $h$, on logarithmic axes.]]


<blockquote>
<blockquote>
As seen
On the right panel the error of the forward and backward quotients falls as $h$,


$$
$$
\max |err| \propto h
\max|err| \propto h,
$$
$$


and centered method gives the best numerical approximation.
while that of the centred quotient falls as $h^{2}$: the centred difference is the best of the three.
</blockquote>
</blockquote>



Revision as of 05:13, 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