The four exercises below come from a practical-work handout written for Matlab created by my beloved teacher [[Person:Gautier List|M. Gautier List]]<ref>{{#cite:Q3733}}</ref>, which we solve here with NumPy and Matplotlib.
The four exercises below come from a practical-work handout written for Matlab created by my beloved teacher M. Gautier List<ref>{{#cite:Q3733}}</ref>, which we solve here with NumPy and Matplotlib.
== Exercise 1 ==
== Exercise 1 ==
Plot, on one and the same graph, with legends, a title, and symbols, the two Gaussian functions on $[-3,3]$:
Plot, on the same graph, with legends, a title, and symbols, the two Gaussian functions on $[-3,3]$:
$$
$$
Line 17:
Line 15:
{{Hidden solution}}
{{Hidden solution}}
The square of the abscissa is written <code>x**2</code>: Python's <code>^</code> is the bitwise exclusive or, so <code>x^2</code> returns a wrong array without raising an error. Both expressions are evaluated element-wise on the whole vector of abscissae, and that is what makes one <code>plot</code> call draw a complete curve.
<blockquote>
Caution: The square is written <code>x**2</code> in Python.: Python's <code>^</code> is the bitwise exclusive OR !
<code>markevery=40</code> places a symbol on every 40th point only: a marker on each of the 400 points would hide the curve it marks.
<blockquote>
<code>markevery=40</code> places a symbol on every 40th point only: a marker on each of the 400 points would flood the curve.
[[File:Two Gaussian densities over -3 to 3.png|thumb|alt=Two bell curves on the interval from minus 3 to 3, the wider in blue with circle markers, the narrower in red with square markers|Both densities on $[-3,3]$, with the markers, the legend, and the title the exercise asks for.]]
</blockquote>
Both densities peak at $x=0$ with $y_1(0)=y_2(0)=1/\sqrt{2\pi}\approx0.3989$. The coefficient $0.25$ makes $y_1$ the wider curve: at $x=1$, $y_1(1)\approx0.3107$ and $y_2(1)\approx0.2420$, and the half-maximum of $y_1$ lies at $x\approx\pm1.665$, against $\pm1.177$ for $y_2$.
[[File:Two Gaussian densities over -3 to 3.png|thumbnail|300px|alt=Two bell curves on the interval from minus 3 to 3, the wider in blue with circle markers, the narrower in red with square markers|Both densities on $[-3,3]$, with the markers, the legend, and the title the exercise asks for.]]
{{End hidden}}
{{End hidden}}
== Exercise 2 ==
== Exercise 2 ==
Plot, on one and the same graph, with legends, a title, and symbols, the four functions:
Plot, on the same graph, with legends, a title, and symbols, the four functions:
# (a) $\exp(-0.5x^{2})/\sqrt{2\pi}$
# (a) $\exp(-0.5x^{2})/\sqrt{2\pi}$
Line 57:
Line 56:
{{Hidden solution}}
{{Hidden solution}}
The handout gives no interval for this exercise, so $[-3,3]$, the interval of Exercise 1, is used. The four curves share one abscissa vector, as they must share a grid to share axes. <code>np.abs</code> is the element-wise absolute value, and the vertical axis is widened because $|x|$ reaches 3 while the other three curves stay inside $[-1,1]$.
<blockquote>
Hint: <code>np.abs</code> calculates the element-wise absolute value.
plt.title("A Gaussian, sine, cosine, and the absolute value on $[-3, 3]$")
plt.title("A Gaussian, sine, cosine, and the absolute value on $[-3, 3]$")
plt.ylim(-1.2, 3.2) # |x| reaches 3, the others stay in [-1, 1]
plt.ylim(-1.2, 3.2)
plt.grid(alpha=0.3)
plt.grid(alpha=0.3)
plt.legend()
plt.legend()
Line 80:
Line 81:
</syntaxhighlight>
</syntaxhighlight>
[[File:Gaussian sine cosine and absolute value over -3 to 3.png|thumb|alt=Four curves on the interval from minus 3 to 3: a Gaussian bump, a sine, a cosine, and a V-shaped absolute value|The four functions of Exercise 2 on a common window.]]
[[File:Gaussian sine cosine and absolute value over -3 to 3.png|thumbnail|300px|alt=Four curves on the interval from minus 3 to 3: a Gaussian bump, a sine, a cosine, and a V-shaped absolute value|The four functions of Exercise 2 on a common window.]]
Three of the curves are smooth; $|x|$ has a corner at $x=0$. It is continuous everywhere and differentiable everywhere except at the origin, where the right derivative is $+1$ and the left derivative $-1$. The function of Exercise 3, $\sin$, has no such point.
{{End hidden}}
{{End hidden}}
Line 96:
Line 95:
$$
$$
With $h\ll1$ the limit is replaced by a finite quotient, which may be taken forward, backward, or centred:
The limit is approximated by a finite $h\ll1$, which may be taken forward, backward, or centred:
$$
$$
Line 108:
Line 107:
{{Hidden solution}}
{{Hidden solution}}
The three quotients are computed from the grid values only, with no symbolic differentiation. The forward and backward quotients return the same list of slopes, and differ only in the point each slope is credited to; the centred quotient has no value at the two end points, since it needs a neighbour on either side.
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.
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 160:
Line 161:
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 168:
Line 169:
</syntaxhighlight>
</syntaxhighlight>
Output:
Expected output:
<pre>
<pre>
Line 176:
Line 177:
</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|thumbnail|300px|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.]]
The one-sided quotient carries a truncation error of 1st order in $h$, the centred quotient one of 2nd order: dividing $h$ by 10 divides the first error by 10 and the second by 100, as the right panel shows. The measured values follow the leading terms,
$$
\frac{h}{2}\,\lvert f''\rvert
$$
for the one-sided quotient and
<blockquote>
On the right panel the error of the forward and backward quotients falls as $h$,
$$
$$
\frac{h^{2}}{6}\,\lvert f'''\rvert
\max|err| \propto h,
$$
$$
for the centred one. At $h=0.5$ these give $0.25$ and $0.0417$ for $f=\sin$, against $0.2471$ and $0.04115$ measured: the coarsest step, where the higher-order terms still matter, is the only one that departs noticeably from its leading term.
while that of the centred quotient falls as $h^{2}$: the centred difference is the best of the three.
</blockquote>
{{End hidden}}
{{End hidden}}
Line 213:
Line 210:
{{Hidden solution}}
{{Hidden solution}}
The exact derivatives, used as references, are
First calculate the exact symbolic derivatives for reference with Sympy:
The grid holds 57 points, $(2.8-(-2.8))/0.1+1$. <code>np.arange(-2.8, 2.8, 0.1)</code> returns 56 of them and stops at $2.7$: the upper bound is excluded, and $5.6/0.1$ evaluates to $55.99\ldots$ in binary floating point. <code>np.linspace</code>, with the number of points computed from the step, includes both end points exactly.
ax[2].set_title("Second derivative, numerical methods and exact")
ax[2].set_title("Second derivative, numerical methods and exact")
Line 314:
Line 323:
</syntaxhighlight>
</syntaxhighlight>
[[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.]]
Expected output:
Reading the errors:
<pre>
points: 57 X[0] = -2.8 X[-1] = 2.8
f' forward max|err| = 2.040e+00
f' backward max|err| = 2.060e+00
f' centred max|err| = 2.000e-02
f' np.gradient max|err| = 2.060e+00
f'' centred max|err| = 4.015e-12
f'' centred, closed ends max|err| = 1.105e-11
f'' np.gradient twice max|err| = 2.140e+01
f'' np.gradient, interior max|err| = 1.165e-12
</pre>
[[File:Cubic polynomial with its numerical derivatives.png|thumbnail|300px|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.]]
<blockquote>
Notice something strange:
<pre>
f'' np.gradient twice max|err| = 2.140e+01
</pre>
This is an error of $21.4$! Astronomical in this case!
But why?
{{Hidden explanation}}
<code>np.gradient</code> is highly accurate on the interior points of a range, where it applies the centred formula
$$
\tilde f'(x_i)=\frac{f_{i+1}-f_{i-1}}{2h},
$$
with $h\ll 1$ (really, really small $h$).
but a centred formula needs points to the left and right of the target point, and the two end points have only a point either to the right or to the left. Hence for $n$ points $x_0,\dots,x_{n-1}$, <code>np.gradient</code> applies the forward/backward formulae:
* At $h=0.1$ the one-sided first difference is off by about 2, not 0.02: the truncation term is $\frac{h}{2}\lvert f''\rvert$, and $\lvert f''\rvert$ reaches $41.6$ at $x=2.8$, so $0.05\cdot41.6=2.08$. It is the steepest end of the interval, not the formula, that sets the maximum.
which is not that accurate: It returns $20.38$ for $f'(-2.8)=21.64$, A second call to <code>np.gradient</code> then divides that error by $2h=0.2$, multiplying the error 5 folds, blowing it increasingly out of proportion.
* The centred first difference is off by $0.0200$, which is exactly $\frac{h^{2}}{6}\lvert f'''\rvert=\frac{0.01}{6}\cdot12$, since $f'''=12$ is constant.
* The centred second difference is exact here: $4\cdot10^{-12}$ is round-off, not truncation. Its truncation error is $\frac{h^{2}}{12}f^{(4)}$, which vanishes for every polynomial of degree 3 or less.
* <code>np.gradient</code> is centred inside and one-sided at the two end points, which is why its maximum error (2.06) is the one-sided error while its interior error is the centred one (0.02).
* Applied twice, <code>np.gradient</code> gives the centred second difference inside (error $1.2\cdot10^{-12}$) but propagates the first-order end formulas outward, with errors of 13.4 at $x=-2.8$ and 21.4 at $x=2.8$. The visible spikes at the ends of the right-hand panel are that artefact, not the function.
The graphs also read as a check on the derivatives: $f'$ vanishes at $x\approx-1.6385$ and $x\approx0.3052$, where $f$ has its local maximum ($f\approx7.857$) and its local minimum ($f\approx0.514$), and $f''$ vanishes at $x=-2/3$, where $f'$ reaches its minimum, $-17/3$. Question 6 of the handout asks for the first derivative to be compared with the exact second derivative, which is a slip in the wording: the second derivatives are compared.
So what is the real solution?
{{Hidden solution}}
Either use really, really $h\ll 1$ (like $10^{-5}$, etc.), or cheat:
Instead of
<syntaxhighlight lang="python" copy>
a, b, h = -2.8, 2.8, 0.1
n = int(round((b - a) / h)) + 1 # 57 points including both end points
X = np.linspace(a, b, n)
</syntaxhighlight>
Write
<syntaxhighlight lang="python" copy>
a, b, h = -2.8, 2.8, 0.1
n = int(round((b - a) / h)) + 1 # 57 points including both end points
X = np.linspace(a-h, b+h, n+2)
</syntaxhighlight>
Then after graphing, discard the two additional points
<syntaxhighlight lang="python" copy>
X=X[1:]
Y=Y[1:]
d1_gradient=d1_gradient[1:]
d2_gradient=d2_gradient[1:]
</syntaxhighlight>
{{End hidden}}
{{End hidden}}
</blockquote>
{{End hidden}}
{{End hidden}}
Latest revision as of 06:08, 20 November 2026
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]$:
Plot, on the same graph, with legends, a title, and symbols, the four functions:
(a) $\exp(-0.5x^{2})/\sqrt{2\pi}$
(b) $\sin(x)$
(c) $\cos(x)$
(d) $|x|$
Hint: np.abs calculates the element-wise absolute value.
importnumpyasnpimportmatplotlib.pyplotaspltx=np.linspace(-3,3,400)gauss=np.exp(-0.5*x**2)/np.sqrt(2*np.pi)plt.figure(figsize=(7,4.2))plt.plot(x,gauss,"-o",markevery=40,label=r"$\exp(-0.5x^2)/\sqrt{2\pi}$")plt.plot(x,np.sin(x),"--s",markevery=40,label=r"$\sin x$")plt.plot(x,np.cos(x),"-.^",markevery=40,label=r"$\cos x$")plt.plot(x,np.abs(x),":d",markevery=40,label=r"$|x|$")plt.xlabel("$x$")plt.ylabel("$y$")plt.title("A Gaussian, sine, cosine, and the absolute value on $[-3, 3]$")plt.ylim(-1.2,3.2)plt.grid(alpha=0.3)plt.legend()plt.show()
The four functions of Exercise 2 on a common window.
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)$.
The three grids are built with np.linspace(-2, 2, n, retstep=True): the number of points is fixed, and the call returns the step dx that the grid really has, which is the step the quotients divide by. np.arange 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.
importnumpyasnpimportmatplotlib.pyplotaspltdefforward(f,h):return(f[1:]-f[:-1])/h# approximation of the derivative at x_idefbackward(f,h):return(f[1:]-f[:-1])/h# same slopes, read as the derivative at x_{i+1}defcentred(f,h):return(f[2:]-f[:-2])/(2*h)# interior points only# 1. the three steps of the questionsteps=[0.5,0.1,0.01]err_forward,err_centred=[],[]forhinsteps: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 hass=np.sin(x)e_fwd=np.max(np.abs(forward(s,dx)-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,dx)-np.cos(x[1:-1])))err_forward.append(e_fwd)err_centred.append(e_cen)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 stepx,h=np.linspace(-2,2,9,retstep=True)# 9 points, so h = 0.5s=np.sin(x)xx=np.linspace(-2,2,400)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(x[:-1],forward(s,h),"o",label=r"forward, $h=0.5$")ax[0].plot(x[1:-1],centred(s,h),"s",label=r"centred, $h=0.5$")ax[0].set_xlabel("$x$")ax[0].set_ylabel(r"$f'(x)$")ax[0].set_title(r"Derivative of $\sin x$ from the grid, $h=0.5$")ax[0].grid(alpha=0.3)ax[0].legend()ax[1].loglog(steps,err_forward,"o-",label="forward / backward")ax[1].loglog(steps,err_centred,"s-",label="centred")ax[1].loglog(steps,np.array(steps)/2,"k--",lw=1,label=r"$\propto h$")ax[1].loglog(steps,np.array(steps)**2/6,"k:",lw=1,label=r"$\propto h^2$")ax[1].set_xlabel("$h$")ax[1].set_ylabel("max|err|")ax[1].set_title("Maximum absolute error against the step")ax[1].grid(alpha=0.3,which="both")ax[1].legend()fig.tight_layout()plt.show()
Expected output:
h = 0.5 n = 9 max|err| forward 2.471e-01 backward 2.471e-01 centred 4.115e-02
h = 0.1 n = 41 max|err| forward 4.999e-02 backward 4.999e-02 centred 1.666e-03
h = 0.01 n = 401 max|err| forward 5.000e-03 backward 5.000e-03 centred 1.667e-05
Left: the quotients at $h=0.5$ against $\cos(x)$. Right: the maximum error against $h$, on logarithmic axes.
In human form,
$$
\begin{cases}
f'(x)=6x^{2}+8x-3 \\
f''(x)=12x+8
\end{cases}
$$
importnumpyasnpimportmatplotlib.pyplotasplt# 1. the function, and its exact derivativesdeff(x):return2*x**3+4*x**2-3*x+1defdf(x):return6*x**2+8*x-3# exact first derivativedefd2f(x):return12*x+8# exact second derivative# 2. the vectors X and Y, with the step h = 0.1a,b,h=-2.8,2.8,0.1n=int(round((b-a)/h))+1# 57 points including both end pointsX=np.linspace(a,b,n)Y=f(X)print("points:",X.size," X[0] =",X[0]," X[-1] =",X[-1])# 3. first derivative, four waysd1_forward=(Y[1:]-Y[:-1])/hd1_backward=(Y[1:]-Y[:-1])/hd1_centred=(Y[2:]-Y[:-2])/(2*h)d1_gradient=np.gradient(Y,h)# 4. second derivative, two waysdefsecond_difference(Y,h):d2=np.empty(Y.size)d2[1:-1]=(Y[2:]-2*Y[1:-1]+Y[:-2])/h**2# centred, interior pointsreturnd2d2_direct=second_difference(Y,h)d2_gradient=np.gradient(d1_gradient,h)# 5. the error of each method against the exact referencesdefreport(name,approx,exact):print(f"{name:<30} max|err| = {np.max(np.abs(approx-exact)):.3e}")report("f' forward",d1_forward,df(X[:-1]))report("f' backward",d1_backward,df(X[1:]))report("f' centred",d1_centred,df(X[1:-1]))report("f' np.gradient",d1_gradient,df(X))report("f'' centred",d2_direct[1:-1],d2f(X[1:-1]))report("f'' centred, closed ends",d2_direct,d2f(X))report("f'' np.gradient twice",d2_gradient,d2f(X))report("f'' np.gradient, interior",d2_gradient[2:-2],d2f(X[2:-2]))# 6. the three graphs of questions 2, 5, and 6fig,ax=plt.subplots(1,3,figsize=(12,3.4))ax[0].plot(X,Y,"-")# question 2ax[0].set_title(r"$y=f(x)$ on $[-2.8,\,2.8]$, $h=0.1$")ax[0].set_xlabel("$x$")ax[0].set_ylabel("$f(x)$")ax[1].plot(X,df(X),"-",color="black",lw=2,label="exact $f'(x)$")# question 5ax[1].plot(X[:-1],d1_forward,"o",ms=3,label="forward")ax[1].plot(X[1:],d1_backward,"x",ms=3,label="backward")ax[1].plot(X[1:-1],d1_centred,"s",ms=2.5,label="centred")ax[1].plot(X,d1_gradient,"--",lw=0.9,label="numpy.gradient")ax[1].set_title("First derivative, numerical methods and exact")ax[1].set_xlabel("$x$")ax[1].set_ylabel("$f'(x)$")ax[1].legend(fontsize=6)ax[2].plot(X,d2f(X),"-",color="black",lw=2,label="exact $f''(x)$")# question 6ax[2].plot(X[1:-1],d2_direct[1:-1],"s",ms=2.5,label="centred 2nd difference")ax[2].plot(X[[0,-1]],d2_direct[[0,-1]],"^",ms=6,label="one-sided 2nd difference")ax[2].plot(X,d2_gradient,":",lw=1.2,label="numpy.gradient twice")ax[2].set_title("Second derivative, numerical methods and exact")ax[2].set_xlabel("$x$")ax[2].set_ylabel("$f''(x)$")ax[2].legend(fontsize=6)foraxisinax:axis.grid(alpha=0.3)fig.tight_layout()plt.show()
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 np.gradient breaks down at both ends.
This is an error of $21.4$! Astronomical in this case!
But why?
np.gradient is highly accurate on the interior points of a range, where it applies the centred formula
$$
\tilde f'(x_i)=\frac{f_{i+1}-f_{i-1}}{2h},
$$
with $h\ll 1$ (really, really small $h$).
but a centred formula needs points to the left and right of the target point, and the two end points have only a point either to the right or to the left. Hence for $n$ points $x_0,\dots,x_{n-1}$, np.gradient applies the forward/backward formulae:
which is not that accurate: It returns $20.38$ for $f'(-2.8)=21.64$, A second call to np.gradient then divides that error by $2h=0.2$, multiplying the error 5 folds, blowing it increasingly out of proportion.
So what is the real solution?
Either use really, really $h\ll 1$ (like $10^{-5}$, etc.), or cheat:
Instead of
a,b,h=-2.8,2.8,0.1n=int(round((b-a)/h))+1# 57 points including both end pointsX=np.linspace(a,b,n)
Write
a,b,h=-2.8,2.8,0.1n=int(round((b-a)/h))+1# 57 points including both end pointsX=np.linspace(a-h,b+h,n+2)
Then after graphing, discard the two additional points