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)$.
h=0.5# modify for different precisionsx=np.arange(-2,2+h/2,h)s=np.sin(x)xx=np.linspace(-2,2,400)importnumpyasnpimportmatplotlib.pyplotaspltdefforward(f,h):return(f[1:]-f[:-1])/h# approximation of derivative of x_idefbackward(f,h):return(f[1:]-f[:-1])/h# same slopes, but considered approximation of derivative of x_{i+1}defcentred(f,h):return(f[2:]-f[:-2])/(2*h)# interior points onlysteps=[0.5,0.1,0.01]err_forward,err_centred=[],[]forhinsteps:x=np.arange(-2,2+h/2,h)# + h/2 keeps x = 2 on the grids=np.sin(x)e_fwd=np.max(np.abs(forward(s,h)-np.cos(x[:-1])))e_bwd=np.max(np.abs(backward(s,h)-np.cos(x[1:])))e_cen=np.max(np.abs(centred(s,h)-np.cos(x[1:-1])))err_forward.append(e_fwd)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}")fig,ax=plt.subplots(1,2,figsize=(10.5,3.8))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 values")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("Error against the step")ax[1].grid(alpha=0.3,which="both")ax[1].legend()fig.tight_layout()plt.show()
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 three quotients at $h=0.5$ against $\cos(x)$. Right: the maximum error against $h$, on logarithmic axes.
and centered method gives the best numerical approximation.
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:
builds the vectors $X$ and $Y$ holding $x$ and $y=f(x)$ with a step $h=0.1$;
plots the curve $y=f(x)$ from $X$ and $Y$;
computes numerically, by several methods, the first derivative of $f$;
computes numerically, by several methods, the second derivative of $f$;
plots, on one graph, the first derivatives of 3 against the exact first derivative;
plots, on one graph, the second derivatives of 4 against the exact second derivative.
The exact derivatives, used as references, are
$$
f'(x)=6x^{2}+8x-3
$$
$$
f''(x)=12x+8
$$
importnumpyasnpdeff(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 derivativea,b,h=-2.8,2.8,0.1n=int(round((b-a)/h))+1# 57 points, both end points includedX=np.linspace(a,b,n)Y=f(X)print("points:",X.size," X[0] =",X[0]," X[-1] =",X[-1])d1_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)# centred inside, one-sided at the two endsd2_centred=(Y[2:]-2*Y[1:-1]+Y[:-2])/h**2d2_gradient=np.gradient(d1_gradient,h)# the first difference applied twicedefreport(name,approx,exact):print(f"{name:<28} 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_centred,d2f(X[1:-1]))report("f'' np.gradient twice",d2_gradient,d2f(X))report("f'' np.gradient, interior",d2_gradient[2:-2],d2f(X[2:-2]))
The same script draws the three graphs of questions 2, 5, and 6:
importnumpyasnpimportmatplotlib.pyplotaspltfig,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_centred,"s",ms=2.5,label="centred 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.