import sympy as sp
x = sp.symbols("x")
f = 2*x**3 + 4*x**2 - 3*x + 1
print("f(x) =", sp.expand(f))
d1, d2 = sp.diff(f, x), sp.diff(f, x, 2)
print()
print("f'(x) =", sp.expand(d1), " -> LaTeX:", sp.latex(d1))
print("f''(x) =", sp.expand(d2), " -> LaTeX:", sp.latex(sp.expand(d2)))
In human form,
$$
\begin{cases}
f'(x)=6x^{2}+8x-3 \\
f''(x)=12x+8
\end{cases}
$$
import numpy as np
import matplotlib.pyplot as plt
# 1. the function, and its exact derivatives
def f(x):
return 2*x**3 + 4*x**2 - 3*x + 1
def df(x):
return 6*x**2 + 8*x - 3 # exact first derivative
def d2f(x):
return 12*x + 8 # exact second derivative
# 2. the vectors X and Y, with the step h = 0.1
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)
Y = f(X)
print("points:", X.size, " X[0] =", X[0], " X[-1] =", X[-1])
# 3. first derivative, four ways
d1_forward = (Y[1:] - Y[:-1]) / h
d1_backward = (Y[1:] - Y[:-1]) / h
d1_centred = (Y[2:] - Y[:-2]) / (2 * h)
d1_gradient = np.gradient(Y, h)
# 4. second derivative, two ways
def second_difference(Y, h):
d2 = np.empty(Y.size)
d2[1:-1] = (Y[2:] - 2*Y[1:-1] + Y[:-2]) / h**2 # centred, interior points
return d2
d2_direct = second_difference(Y, h)
d2_gradient = np.gradient(d1_gradient, h)
# 5. the error of each method against the exact references
def report(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 6
fig, ax = plt.subplots(1, 3, figsize=(12, 3.4))
ax[0].plot(X, Y, "-") # question 2
ax[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 5
ax[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 6
ax[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)
for axis in ax:
axis.grid(alpha=0.3)
fig.tight_layout()
plt.show()
Notice something strange:
f'' np.gradient twice max|err| = 2.140e+01
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:
$$
\tilde f'(x_0)=\frac{f_1-f_0}{h}, \qquad \tilde f'(x_{n-1})=\frac{f_{n-1}-f_{n-2}}{h},
$$
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.1
n = int(round((b - a) / h)) + 1 # 57 points including both end points
X = np.linspace(a, b, n)
Write
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)
Then after graphing, discard the two additional points
X=X[1:]
Y=Y[1:]
d1_gradient=d1_gradient[1:]
d2_gradient=d2_gradient[1:]