Jump to content

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

From Wikibase
Exercise 4: exact derivatives derived with SymPy instead of assumed, the two snippets merged into one script with numbered sections, and a section explaining why the double np.gradient fails at the ends, with the 4-point closure that fixes it. AI-assisted (RonzzWikiCowriter) (via update-page on MediaWiki MCP Server)
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
Reference: [[Ordinary derivative#Formal definition|Formal definition]]
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 [[Person:Gautier List|M. Gautier List]]<ref>{{#cite:Q3733}}</ref>, which we solve here with NumPy and Matplotlib.


Line 44: Line 42:
</blockquote>
</blockquote>


[[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.]]
[[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}}


Line 83: 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.]]


{{End hidden}}
{{End hidden}}
Line 171: Line 169:
</syntaxhighlight>
</syntaxhighlight>


Output:
Expected output:


<pre>
<pre>
Line 179: Line 177:
</pre>
</pre>


[[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.]]
[[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.]]


<blockquote>
<blockquote>
Line 212: Line 210:
{{Hidden solution}}
{{Hidden solution}}


The exact derivatives, used as references, follow from the power rule applied term by term, which SymPy carries out rather than the reader taking it on trust:
First calculate the exact symbolic derivatives for reference with Sympy:


<syntaxhighlight lang="python" class="pyodide" copy>
<syntaxhighlight lang="python" class="pyodide" copy>
Line 219: Line 217:
x = sp.symbols("x")
x = sp.symbols("x")
f = 2*x**3 + 4*x**2 - 3*x + 1
f = 2*x**3 + 4*x**2 - 3*x + 1
print("f(x) =", sp.expand(f))
print("f(x) =", sp.expand(f))
print()
for term in sorted(sp.Add.make_args(f), key=lambda t: -sp.degree(t, x)):
    print(f"  d/dx  ({str(term):<6}) = {sp.diff(term, x)}")
    print(f"  d2/dx2({str(term):<6}) = {sp.diff(term, x, 2)}")
d1, d2 = sp.diff(f, x), sp.diff(f, x, 2)
d1, d2 = sp.diff(f, x), sp.diff(f, x, 2)
print()
print()
Line 232: Line 224:
</syntaxhighlight>
</syntaxhighlight>


Output:
Expected output:


<pre>
<pre>
f(x) = 2*x**3 + 4*x**2 - 3*x + 1
f(x) = 2*x**3 + 4*x**2 - 3*x + 1
  d/dx  (2*x**3) = 6*x**2
  d2/dx2(2*x**3) = 12*x
  d/dx  (4*x**2) = 8*x
  d2/dx2(4*x**2) = 8
  d/dx  (-3*x  ) = -3
  d2/dx2(-3*x  ) = 0
  d/dx  (1    ) = 0
  d2/dx2(1    ) = 0
f'(x)  = 6*x**2 + 8*x - 3  ->  LaTeX: 6 x^{2} + 8 x - 3
f'(x)  = 6*x**2 + 8*x - 3  ->  LaTeX: 6 x^{2} + 8 x - 3
f''(x) = 12*x + 8  ->  LaTeX: 12 x + 8
f''(x) = 12*x + 8  ->  LaTeX: 12 x + 8
</pre>
</pre>


so the references are
In human form,
 
$$
$$
\begin{cases}
\begin{cases}
Line 258: Line 239:
\end{cases}
\end{cases}
$$
$$
One script answers the six questions, each under its own numbered section:


<syntaxhighlight lang="python" class="pyodide" copy>
<syntaxhighlight lang="python" class="pyodide" copy>
Line 277: Line 256:
# 2. the vectors X and Y, with the step h = 0.1
# 2. the vectors X and Y, with the step h = 0.1
a, b, h = -2.8, 2.8, 0.1
a, b, h = -2.8, 2.8, 0.1
n = int(round((b - a) / h)) + 1          # 57 points, both end points included
n = int(round((b - a) / h)) + 1          # 57 points including both end points
X = np.linspace(a, b, n)
X = np.linspace(a, b, n)
Y = f(X)
Y = f(X)
Line 287: Line 266:
d1_backward = (Y[1:] - Y[:-1]) / h
d1_backward = (Y[1:] - Y[:-1]) / h
d1_centred  = (Y[2:] - Y[:-2]) / (2 * h)
d1_centred  = (Y[2:] - Y[:-2]) / (2 * h)
d1_gradient = np.gradient(Y, h)         # centred inside, one-sided at the two ends
d1_gradient = np.gradient(Y, h)  


# 4. second derivative, two ways
# 4. second derivative, two ways
Line 293: Line 272:
     d2 = np.empty(Y.size)
     d2 = np.empty(Y.size)
     d2[1:-1] = (Y[2:] - 2*Y[1:-1] + Y[:-2]) / h**2            # centred, interior points
     d2[1:-1] = (Y[2:] - 2*Y[1:-1] + Y[:-2]) / h**2            # centred, interior points
    d2[0]    = (2*Y[0]  - 5*Y[1]  + 4*Y[2]  - Y[3] ) / h**2  # 4-point closure, left end
    d2[-1]  = (2*Y[-1] - 5*Y[-2] + 4*Y[-3] - Y[-4]) / h**2  # 4-point closure, right end
     return d2
     return d2


d2_direct  = second_difference(Y, h)
d2_direct  = second_difference(Y, h)
d2_gradient = np.gradient(d1_gradient, h)     # kept to show why it fails at the ends
d2_gradient = np.gradient(d1_gradient, h)


# 5. the error of each method against the exact references
# 5. the error of each method against the exact references
Line 346: Line 323:
</syntaxhighlight>
</syntaxhighlight>


Output:
Expected output:


<pre>
<pre>
Line 360: Line 337:
</pre>
</pre>


[[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|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.]]


=== Why the double <code>np.gradient</code> breaks down at the ends ===
<blockquote>
Notice something strange:


<code>np.gradient</code> is exact on the interior points, where it applies the centred formula
<pre>
f'' np.gradient twice          max|err| = 2.140e+01
</pre>


$$
This is an error of $21.4$! Astronomical in this case!
\tilde f'(x_i)=\frac{f_{i+1}-f_{i-1}}{2h},
$$


but a centred formula needs a point on each side, and the two end points have none. numpy closes the array there with the 2-point one-sided difference of the default <code>edge_order=1</code>,
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_0)=\frac{f_1-f_0}{h}, \qquad \tilde f'(x_{n-1})=\frac{f_{n-1}-f_{n-2}}{h},
\tilde f'(x_i)=\frac{f_{i+1}-f_{i-1}}{2h},
$$
$$


which is only first-order accurate: it returns $20.38$ for $f'(-2.8)$, against the exact $21.64$. A second call then divides that error by $2h=0.2$, so one wrong slope at an end injects an error of order $1$ into the neighbouring second difference, which is what the $2.1\cdot10^{1}$ above measures, at the two ends and nowhere else.
with $h\ll 1$ (really, really small $h$).


The end values of the double call can be written out exactly. Substituting the two end formulas in the centred second difference gives
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:


$$
$$
\begin{cases}
\tilde f'(x_0)=\frac{f_1-f_0}{h}, \qquad \tilde f'(x_{n-1})=\frac{f_{n-1}-f_{n-2}}{h},
\tilde f''(x_0)=\dfrac{f_0-2f_1+f_2}{2h^{2}}=\dfrac{1}{2}\tilde f''_{\mathrm{c}}(x_1) \\
\tilde f''(x_{n-1})=\dfrac{f_{n-3}-2f_{n-2}+f_{n-1}}{2h^{2}}=\dfrac{1}{2}\tilde f''_{\mathrm{c}}(x_{n-2})
\end{cases}
$$
$$


where $\tilde f''_{\mathrm{c}}$ is the centred second difference, so the double call reports, at each end, half the second derivative of the neighbouring point, at the wrong abscissa: $-12.2$ instead of $-25.6$, and $20.2$ instead of $41.6$.
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.


Raising <code>edge_order=2</code> repairs the two end slopes, but a second difference built from first differences still loses an order: the error then decays as $h$, that is by a factor $2$ at each halving, and it stands at $9.0\cdot10^{-1}$ on this cubic, whose second derivative the direct centred formula reproduces to $4.0\cdot10^{-12}$.
So what is the real solution?


The fix is to close the second difference itself, with a 4-point one-sided formula at each end:
{{Hidden solution}}
Either use really, really $h\ll 1$ (like $10^{-5}$, etc.), or cheat:


$$
Instead of
\begin{cases}
\tilde f''(x_i)=\dfrac{f_{i+1}-2f_i+f_{i-1}}{h^{2}} \quad 1\le i\le n-2 \\
\tilde f''(x_0)=\dfrac{2f_0-5f_1+4f_2-f_3}{h^{2}} \\
\tilde f''(x_{n-1})=\dfrac{2f_{n-1}-5f_{n-2}+4f_{n-3}-f_{n-4}}{h^{2}}
\end{cases}
$$


The $2,-5,4,-1$ stencil is exact on a cubic, and second-order accurate otherwise, so both ends join the interior at the same order. That is the <code>second_difference</code> function of the script, and it takes the maximum error from $2.1\cdot10^{1}$ to $1.1\cdot10^{-11}$. On a function that is not a polynomial, where the error is a genuine truncation error, the defect of the double call stands out further, because it does not shrink with $h$ at all while the closure drops by a factor $4$ at each halving:
<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>


<syntaxhighlight lang="python" class="pyodide" copy>
Write
import numpy as np


def second_difference(Y, h):
<syntaxhighlight lang="python" copy>
    d2 = np.empty(Y.size)
a, b, h = -2.8, 2.8, 0.1
    d2[1:-1] = (Y[2:] - 2*Y[1:-1] + Y[:-2]) / h**2
n = int(round((b - a) / h)) + 1          # 57 points including both end points
    d2[0]    = (2*Y[0]  - 5*Y[1]  + 4*Y[2]  - Y[3] ) / h**2
X = np.linspace(a-h, b+h, n+2)
    d2[-1]  = (2*Y[-1] - 5*Y[-2] + 4*Y[-3] - Y[-4]) / h**2
</syntaxhighlight>
    return d2


# a function that is not a polynomial, so the error is a genuine truncation error
Then after graphing, discard the two additional points
g  = lambda t: np.exp(0.3 * t)
d2g = lambda t: 0.3**2 * np.exp(0.3 * t)


for n in (57, 113, 225):
<syntaxhighlight lang="python" copy>
    X, h = np.linspace(-2.8, 2.8, n, retstep=True)
X=X[1:]
    Y = g(X)
Y=Y[1:]
    e_closed = np.max(np.abs(second_difference(Y, h) - d2g(X)))
d1_gradient=d1_gradient[1:]
    e_nested = np.max(np.abs(np.gradient(np.gradient(Y, h), h) - d2g(X)))
d2_gradient=d2_gradient[1:]
    print(f"h = {h:.4f}  closed {e_closed:.2e}  nested {e_nested:.2e}")
</syntaxhighlight>
</syntaxhighlight>


Output:
{{End hidden}}
 
{{End hidden}}
<pre>
</blockquote>
h = 0.1000  closed 1.66e-04  nested 1.07e-01
h = 0.0500  closed 4.23e-05  nested 1.06e-01
h = 0.0250  closed 1.07e-05  nested 1.05e-01
</pre>
 
The whole error of the double call sits at the two ends, where it is about half the second derivative itself, while the interior still converges at second order: restricting the comparison to the interior points gives $5.7\cdot10^{-5}$, $1.5\cdot10^{-5}$, and $3.8\cdot10^{-6}$.
 
{{End hidden}}
{{End hidden}}



Latest revision as of 06:08, 20 November 2026

Languages: English · français · Esperanto

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